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

前端 未结 5 2131
春和景丽
春和景丽 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:44

    There are two more options I don't see mentioned in any of the other answers. I've left the grep/grep/awk/head pipeline intact for demonstration purposes, even though (as alluded to in rici's answer) it could be reduced to something like

    awk -F ' ' '/MapReduceNod[e]/ {print $2; exit}'
    
    1. Using double quotes for the whole ssh command:

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

      Notice that I can use single quotes in the command now, but I have to escape other things I don't want expanded yet: \$() (which I've used instead of backticks), double quotes \", and print \$2.

    2. A here-doc with quoted delimiter:

      ssh -T deploy@hera <<'EOF'
      kill -9 $(ps -ef | grep MapReduceNode | grep -v 'grep' |
      awk -F ' ' '{print $2}' | head -n 1)
      EOF
      

      The -T prevents ssh from complaining about not allocating a pseudo-terminal.

      The here-doc with quoted delimiter is extra nice because its contents don't have to be modified at all with respect to escaping things, and it can contain single quotes.

提交回复
热议问题