Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting a conditional RUN statement inside a dockerfile

I am trying to write a docker file which will run a RUN command to search for a word in a package.json file and act upon it:

this is my simple dockerfile:

FROM ubuntu:14.04  COPY package.json package.json  RUN if grep -q "grunt" package.json; then echo succeed fi 

as you can see i just want a simple if statement but it get this error:

Step 2 : RUN if grep -q "grunt" package.json; then echo succeed fi  ---> Running in af460df45239 /bin/sh: 1: Syntax error: end of file unexpected (expecting "fi") INFO[0001] The command [/bin/sh -c if grep -q "grunt" package.json; then echo succeed fi] returned a non-zero code: 2 

How should i run my command? thanks.

like image 220
lobengula3rd Avatar asked May 10 '15 21:05

lobengula3rd


People also ask

Can we add if condition in Dockerfile?

Accepted answer does not cover "if else condition" part of the question. Would be better to rename it to "Dockerfile with external arguments" if condition check didn't mean to be a requirement.

How do I create a Run command in Dockerfile?

The basic syntax for the command is: docker run [OPTIONS] IMAGE [COMMAND] [ARG...] You can run containers from locally stored Docker images. If you use an image that is not on your system, the software pulls it from the online registry.

Can Dockerfile have multiple run commands?

You can separate your commands with ; or && . If you use the second method, and one of the commands fails, the docker build also fails. This is usually a good idea.

Can you run Docker commands in Dockerfile?

You can't run Docker commands from a Dockerfile (and shouldn't as a general rule try to run Docker commands from within Docker containers) but you can write an ordinary shell script on the host that runs the docker build && docker run .


1 Answers

Just like when typing at the shell, you need either a newline or a semicolon before fi:

RUN if grep -q "grunt" package.json; then echo succeed; fi                                              add this ^ 
like image 192
jwodder Avatar answered Sep 20 '22 08:09

jwodder