The code does not work with sh -c, but works directly on sh

$ sh
sh-3.2$ if
> ps -ef | grep apple ;
> then
> echo APPLE 
> fi ;
lazer   7584  7571  0 04:36 pts/4    00:00:00 grep apple
APPLE
sh-3.2$ exit
exit
$ which sh
/bin/sh
$ /bin/sh -c if ps -ef | grep apple ; then echo APPLE fi ;
bash: syntax error near unexpected token `then'
$

As above, my simple if statement works as expected when executing line by line, but gives me the following error when executed with sh -c:

bash: syntax error next to unexpected `then 'token

What am I missing here?

+3
source share
1 answer

Your interactive shell will avoid calling with sh -c. In particular, he accepts everything that follows after as a colon as a new statement.

Send everything you feed /bin/sh, for example.

$ /bin/sh -c "if ps -ef | grep apple ; then echo APPLE fi ;"

, , , , , , Heredoc.

+2

All Articles