How to use bash $(awk) in single ssh-command?

2019-01-11 01:42发布

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.

标签: bash ssh awk
5条回答
聊天终结者
2楼-- · 2019-01-11 01:58

What about piping the output of the command and run awk locally?

ssh yourhost uname -a | awk '{ print $2 } '
查看更多
疯言疯语
3楼-- · 2019-01-11 02:10

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
查看更多
劫难
4楼-- · 2019-01-11 02:11

If you are trying to get the hostname, use:

ssh myServer "uname -n"

查看更多
女痞
5楼-- · 2019-01-11 02:21

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}'
查看更多
闹够了就滚
6楼-- · 2019-01-11 02:24

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}'\` "
查看更多
登录 后发表回答