Using backticks (`) over ssh in a script [duplicat

2019-02-19 07:22发布

问题:

This question already has an answer here:

  • is it possible to use variables in remote ssh command? 2 answers

I have a command that, when I run locally, I use backticks in to get that output of the commands contained within them and I want to send this over ssh (this isn't the actual command but a shortened example)

cat `ls -alr | grep 'someregex'`

I tried using

ssh -f hostname cat `ls | grep 'someregex'`

however this doesn't act as I was expecting and instead executes the backticks locally, does anyone know a way around this?

回答1:

Try enclosing the command in quotes:

ssh -f hostname 'cat `ls | grep "someregex"`'

Note that the inner quotes have to be replaced with double quotes.

Also, note that you can't enclose the whole command in double quotes, because bash will expand the subshell locally before it invokes ssh. For example, compare the following commands:

$ echo "`echo foo`"
foo
$ echo '`echo foo`'
`echo foo`


标签: bash shell ssh