Lazer
Lazer

Reputation: 94930

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

$ 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?

Upvotes: 3

Views: 496

Answers (1)

Brian Agnew
Brian Agnew

Reputation: 272347

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/sh e.g.

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

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.

Upvotes: 2

Related Questions