130

I need to run 2 commands with docker exec. I am copying a file out of the docker container and don't want to have to deal with credentials to use something like ssh. This command copies a file:

sudo docker exec boring_hawking tar -cv /var/log/file.log | tar -x

But it creates a subdirectory var/log, I want to avoid that so if I could do these in the docker container I should be good:

cd /var/log ; tar -cv ./file.log

How can I make docker exec run 2 commands?

Solx
  • 4,611
  • 5
  • 26
  • 29

4 Answers4

194

This led to the answer: Escape character in Docker command line I ended up doing this:

sudo docker exec boring_hawking bash -c 'cd /var/log ; tar -cv ./file.log' | tar -x

So it works by, sort of, running the one bash command with a parameter that is the 2 commands I want to run.

Community
  • 1
  • 1
Solx
  • 4,611
  • 5
  • 26
  • 29
  • 1
    If you have got double quotations inside the command, then you can do as such `-c "cd /var/log; tar -cv \"$1\""` if the file is at parameter 1. – zed Jun 26 '19 at 11:36
48

For anyone else who stumbles across this and wants a different way to specify multiple commands in order to execute a more complex script:

cat <<EOF | docker exec --interactive boring_hawking sh
cd /var/log
tar -cv ./file.log
EOF
zbrunson
  • 1,587
  • 1
  • 12
  • 13
  • 1
    This is a very nice readable solution when you want to execute a more complex script. It deserves more up votes ;) – Slava Fomin II Dec 23 '19 at 17:14
  • 3
    i'm getting a `the input device is not a TTY` error with this method – Roy Shilkrot Jan 09 '20 at 05:09
  • The `--interactive` is supposed to take care of that, if that is not the case then I'm not sure what is going on without having broader context on how you are using this. – zbrunson Jan 10 '20 at 06:59
  • 1
    @Roy try the -t ? – ntg Jan 20 '21 at 07:58
  • 2
    Note: If your script contains variables, you need to escape the `$`. For example: `for i in {1..5}; do echo "Welcome \$i times"; done` (use `\$i` in the echo!) – Philipp Aug 24 '21 at 09:53
  • Take care not to specify the `-t` flag, just `-i` or `--interactive`, otherwise you'll have the `the input device is not a TTY` error. – joliver Mar 23 '23 at 18:22
44

Quite often, the need for several commands is to change the working directory — as in the OP's question.

For that, docker now has a -w option to specify the working directory. E.g. in the present case

docker exec -w /var/log boring_hawking tar -cv ./file.log
P-Gn
  • 23,115
  • 9
  • 87
  • 104
6

If anyone else came here for the awesome answer, but also wants a better way to solve OP's original problem (OP's OP..?) to copy a file out of a docker container, there is now a docker cp command that will do this: https://docs.docker.com/engine/reference/commandline/cp/

Will the Thrill
  • 113
  • 1
  • 8