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
What about piping the output of the command and run awk locally?
ssh yourhost uname -a | awk '{ print $2 } '
The workaround is to create an sh file with the command then pass it to ssh command:
test.sh
echo `uname -a | awk '{print $2}'`
and command:
ssh myServer 'bash -s' < test.sh
UPDATE:
The command without quotes works fine as well:
ssh myServer uname -a | awk '{print $2}'
If you are trying to get the hostname, use:
ssh myServer "uname -n"
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
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}'\` "
$
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
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?