Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

ssh

quoting

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 and kill it. Therefore I do:

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

The problem here is that the awk tokenization step needs single quotes and these clash with the single quote utilized for executing the remote command via ssh. How can these single quotes be escaped?

like image 253
SkyWalker Avatar asked Dec 10 '13 15:12

SkyWalker


People also ask

How do I escape a quote from a bash string?

Bash escape character is defined by non-quoted backslash (\). It preserves the literal value of the character followed by this symbol. Normally, $ symbol is used in bash to represent any defined variable.

How do you escape a single quote in terminal?

A single quote is not used where there is already a quoted string. So you can overcome this issue by using a backslash following the single quote. Here the backslash and a quote are used in the “don't” word.

How do you escape a single quote in Linux?

It's done by finishing already opened one ( ' ), placing escaped one ( \' ), then opening another one ( ' ). This syntax works for all commands.

What does single quote do in bash?

3.1. 2.2 Single Quotes Enclosing characters in single quotes (' ' ') preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.


1 Answers

Use

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

Explanation:

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

1) First string with beginning of command: 'kill -9 `ps -ef | grep MapReduceNode | grep -v "grep" | awk -F " " '

2) Second string with only a single ' char: "'"

3) Third string with the print command: '{print $2}'

4) Fourth string with another single quote: "'"

5) Fifth string with rest of command: ' | head -n 1`'

like image 106
RedX Avatar answered Oct 07 '22 05:10

RedX