6

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?

Aaron
  • 311
  • 3
  • 9
  • Could you clarify on where you think this is duplicated? – Aaron Sep 09 '15 at 11:07
  • It about where the shell constructs (including the backtick **and** the variables) are resolved. – Martin Prikryl Sep 09 '15 at 11:33
  • Use `$(...)` instead of backquotes. – chepner Sep 09 '15 at 12:14
  • ahh yes, I see what you mean now, but I wouldn't have said the connection is immediately obvious, does closing as a duplicate keep the comments so that it's easier for anyone else who comes across this thread to make that connection? – Aaron Sep 09 '15 at 14:48

1 Answers1

9

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`
Will Vousden
  • 32,488
  • 9
  • 84
  • 95
  • 4
    Why not just use double quotes and avoid escaping altogether? – Tom Fenech Sep 09 '15 at 10:55
  • Sure, you can do that too. But I thought a direct fix for the OP's command would be more instructive :) – Will Vousden Sep 09 '15 at 10:59
  • Just an observation, if you want to display the content of the remote file with cat you cant use ls -alr, you have to use the single ls – PerroVerd Sep 09 '15 at 11:05
  • 1
    @PerroVerd True, but the `grep` might take care of that with non-capturing groups (and it might be necessary to inspect file attributes). – Will Vousden Sep 09 '15 at 11:13
  • I noticed that and changed my original post, the original script greps for the date an then cuts it down, my fault for leaving it in I'm currently testing this solution, but the original commands need some editing – Aaron Sep 09 '15 at 11:13
  • You cannot (easily) escape single quotes inside single quotes. – tripleee Sep 10 '15 at 06:02
  • @tripleee You're quite right – I've updated the answer. – Will Vousden Sep 10 '15 at 09:14