How to use bash $(awk) in single ssh-command?
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
Just some additional note:
In my case, the escape of the $
doesn't help:
ts1350:> ssh sysadm@node "grep feature features.txt| awk '{print $6}' "
Password:
A feature -name ue_trace_mme | off
ts1350:> ssh sysadm@node "grep feature features.txt| awk '{print \$6}' "
Password:
awk: cmd. line:1: {print \}
awk: cmd. line:1: ^ backslash not last character on line
awk: cmd. line:1: {print \}
awk: cmd. line:1: ^ syntax error
ts1350:> ssh sysadm@node "grep feature features.txt| awk '{print \\$6}' "
Password:
awk: cmd. line:1: {print \\}
awk: cmd. line:1: ^ backslash not last character on line
awk: cmd. line:1: {print \\}
awk: cmd. line:1: ^ syntax error
While add a space
between $
and the number works:
Fri Oct 4 14:49:28 CEST 2019
ts1350:> ssh sysadm@node "grep feature features.txt| awk '{print $ 6}' "
Password:
off
Hope this secodnary way help someone like me.
Thanks to @dave in his answer: How to print a specific column with awk on a remote ssh session?
What about piping the output of the command and run awk locally?
ssh yourhost uname -a | awk '{ print $2 } '