I am trying to execute a single command over ssh
that contains `sub-code` or $(sub-code) (I use it all the time but I don't know the official name for that) to be executed first, but on the target server.
For the sake of argument, let's say this is the command I want to use. Ofcourse this can be done with hostname
, but this is just a simplified example that contains all the formatting wizardry I want to use.
echo `uname -a | awk '{print $2}'`
No problem. But how do you escape this properly to send it over ssh
in a single command? The following is wrong, because it lets the server reply your local hostname. The sub-code is executed locally:
ssh myServer echo `uname -a | awk '{print $2}'`
But any escape-ishness that comes to mind doesn't work:
$ ssh myServer echo \`uname -a | awk '{print $2}'\` awk: cmd. line:1: {print $2}` awk: cmd. line:1: ^ invalid char '`' in expression $ ssh myServer echo \$(uname -a | awk '{print $2}') bash: syntax error near unexpected token `(' $ ssh myServer echo \$\(uname -a | awk '{print $2}') bash: syntax error near unexpected token `)' $ ssh myServer echo \$\(uname -a | awk '{print $2}'\) awk: cmd. line:1: {print $2}) awk: cmd. line:1: ^ syntax error bash: -c: line 0: unexpected EOF while looking for matching `)' bash: -c: line 1: syntax error: unexpected end of file
I would like an answer that includes using properly escaped ` or $() because I'd like to know if it's possible.
echo` could be something more complicated.
In order to tell awk to use that file for its program, you type: awk -f source-file input-file1 input-file2 … The -f instructs the awk utility to get the awk program from the file source-file (see Command-Line Options). Any filename can be used for source-file .
You can cut in awk using awk's function split . You can also filter records using a regex condition within awk, making grep and cut superfluous. This breaks down like: Set the output field separator to be a pipe between two spaces.
Try this
ssh myServer "uname -a | awk '{print \$2}' "
Use the double quotes "
in order to group the commands you will execute remotely.
You also need to escape the $
in the $2
argument, so that it is not calculated locally, but passed on to awk
remotely.
Edit:
If you want to include the $(
)
, you again have to escape the $
symbol, like this:
ssh myServer "echo \$(uname -a | awk '{print \$2}') "
You can also escape the backtick `, like this:
ssh myServer "echo \`uname -a | awk '{print \$2}'\` "
It is better to use a heredoc with ssh
to avoid escaping quotes everywhere in a more complex command:
ssh -T myServer <<-'EOF' uname -a | awk '{print $2}' exit EOF
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With