$ 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 executed line by line but gives me the following error when executed using sh -c:
bash: syntax error near unexpected token `then’
What am I missing here?
Your interactive shell will be escaping the invocation via
sh -c. In particular it’s taking everyting after the semi-colon as a new statement.Quote everything that you’re feeding to
/bin/she.g.I think you may also need to delimit further using semi-colons given that you’re condensing everything onto one line, and would perhaps suggest you could use a heredoc.