3

I am passing the following command straight through SSH:

ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -i /key/path [email protected] 'bash -s' << EOF
FPM_EXISTS=`ps aux | grep php-fpm`
if [ ! -z "$FPM_EXISTS" ]
then
        echo "" | sudo -S service php5-fpm reload
fi
EOF

I get the following error:

[2015-02-25 22:45:23] local.INFO: bash: line 1: syntax error near unexpected token `('
bash: line 1: ` FPM_EXISTS=root      2378  0.0  0.9 342792 18692 ?        Ss   17:41   0:04 php-fpm: master process (/etc/php5/fpm/php-fpm.conf)                 

It's like it is trying to execute the output of ps aux | grep php-fpm instead of just capturing git the variable. So, if I change the command to try to capture ls, it acts like it tries to execute that as well, of course returning "command not found" for each directory.

If I just paste the contents of the Bash script into a file and run it it works fine; however, I can't seem to figure out how to pass it through SSH.

Any ideas?

2 Answers 2

9

You need to wrap starting EOF in single quotes. Otherwise ps aux | grep php-fpm would get interpreted by the local shell.

The command should look like this:

ssh ... [email protected] 'bash -s' << 'EOF'
FPM_EXISTS=$(ps aux | grep php-fpm)
if [ ! -z "$FPM_EXISTS" ]
then
        echo "" | sudo -S service php5-fpm reload
fi
EOF

Check this: http://tldp.org/LDP/abs/html/here-docs.html (Section 19.7)


Btw, I would encourage you to use $() instead of backticks consequently for command substitution because of the ability to nest them. You will have more fun, believe me. Check this for example: What is the benefit of using $() instead of backticks in shell scripts?

Sign up to request clarification or add additional context in comments.

Comments

5

You should wrap the EOF in single quotes.

ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -i /key/path [email protected] 'bash -s' << 'EOF'
FPM_EXISTS=`ps aux | grep php-fpm`
if [ ! -z "$FPM_EXISTS" ]
then
        echo "" | sudo -S service php5-fpm reload
fi
EOF

4 Comments

Wondering what makes out the difference compared to my answer? (Except the missing explanation)
The time of posting. (Eh, nevermind - but it was nearly the same time. ;)
@hek2mgl, sorry my friend. At the time I started writing & testing my answer, I didn't see that you had already written something.
also it is not a "race". however, I really saw guys copying posts... sorry for blaming you! +1 nice answer ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.