How to escape the single quote character in an ssh / remote bash command?

前端 未结 5 2146
春和景丽
春和景丽 2020-12-01 07:51

I\'m building a small set of scripts for remotely starting, stopping and checking the status of a process. The stop of these scripts should look for a process a

5条回答
  •  孤城傲影
    2020-12-01 08:42

    You can't include a single quote in a single-quoted string. However, that doesn't matter because a single argument can have more than one quoted segment (as long as there is no unquoted whitespace or other self-delimiting characters.)

    For example:

    ssh deploy@hera 'kill -9 `ps -ef |
                     grep MapReduceNode |
                     grep -v "grep" |
                     awk -F " " '\''{print $2}'\'" |
                     head -n 1`"
    

    However, that command line is very clunky. If possible, you should use the pkill utility, which would reduce all that to ssh deploy@hera 'pkill -SIGKILL MapReduceNode'.

    Otherwise you could do all the string manipulation in a single awk invocation (untested, but I think it will work):

    ssh deploy@hera 'ps -ef |
                     awk "/[M]apReduceNode/{system(\"kill -9 \"$2)}"'
    

    (unlike the original, this will kill all MapReduceNode tasks rather than some arbitrary first one. If you really want to just do in one task, add ; exit to the awk action.)

提交回复
热议问题