Search code examples
bashawksshpidps

Error when running bash command over ssh


When trying to run the following command over ssh:

ssh hostname 'for pid in $(ps -ef | grep "some process" | awk '{print $2}'); do kill -9 $pid; done'

I get the following error:

awk: cmd. line:1: {print
awk: cmd. line:1:       ^ unexpected newline or end of string

I've tried escaping in different ways but haven't found the correct way - or maybe it's something else?

Thanks in advance!


Solution

  • You cannot include single quotes into a single-quoted string, since nothing is interpreted inside, except the single quote that closes the string. You can concatenate the single-quoted strings with "'":

    ssh host 'for pid in $(ps -ef | grep "some process" | awk '"'"'{print $2}'"'"'); do kill -9 $pid; done'
    

    Alternatively, concatenate escaped single quotes (\'):

    ssh host 'for pid in $(ps -ef | grep "some process" | awk '\''{print $2}'\''); do kill -9 $pid; done'
    

    See Strong Quoting.

    The Cause of the Error

    Your command is interpreted as a couple of $IFS-separated arguments:

    • for pid in $(ps -ef | grep "some process" | awk {print
    • }); do kill -9 $pid; done

    There is no $2 in the strings, since $2 is interpreted as a shell variable, and the value of this variable in the normal shell context is empty.

    Thus, you have sent the following command to the server:

    for pid in $(ps -ef | grep "some process" | awk {print }); do kill -9 $pid; done
    

    If you run this command in a terminal, you will get the same error from AWK.