63

Here is a silly example of running multiple commands via the CMD instruction in shell-form. I would prefer to use the exec-form, but I don't know how to concatenate the instructions.

shell-form:

CMD mkdir -p ~/my/new/directory/ \
 && cd ~/my/new/directory \
 && touch new.file

exec-form:

CMD ["mkdir","-p","~/my/new/directory/"]
# What goes here?

Can someone provide the equivalent syntax in exec-form?

Zak
  • 12,213
  • 21
  • 59
  • 105

2 Answers2

116

The short answer is, you cannot chain together commands in the exec form.

&& is a function of the shell, which is used to chain commands together. In fact, when you use this syntax in a Dockerfile, you are actually leveraging the shell functionality.

If you want to have multiple commands with the exec form, then you have do use the exec form to invoke the shell as follows...

CMD ["sh","-c","mkdir -p ~/my/new/directory/ && cd ~/my/new/directory && touch new.file"]
Zak
  • 12,213
  • 21
  • 59
  • 105
  • the `sh` initial command was what I forgot to pre-pend - the exec form doesn't take or use SHELL – Josh E Oct 18 '17 at 18:18
  • 3
    Even though the _exec form_ is recommended, in this case I can see only **disadvantages**, compared to the OP's _shell form_: 1. You have to explicitely specify the shell, 2. you have to take care of possibly escaping quotes, 3. you cannot split it into multiple lines for easier readability. Is there any **advantage** as well? Despite of it being just best practice? – Tobias Sep 30 '20 at 12:05
  • Docker will convert the shell form in the original question to exactly this exec-form syntax (possibly customized with an alternate `SHELL`) and I don't think there's any particular reason to write it this way. – David Maze Jul 16 '22 at 12:56
0

I would argue though that these commands should be execute with at a RUN step rather than CMD.

RUN  mkdir -p ~/my/new/directory/ && \
     cd ~/my/new/directory && \
     touch new.file
Ivasan
  • 101
  • 1
  • 7