9

I want to nest multiple strings like this :

sudo ssh server "awk "/pattern/{print "hello"}1" file > file.tmp"

With 2 nested quotes I managed to make my command works :

awk "/pattern/{print \"hello\"}1" file > file.tmp

I cannot use single quote (') because there are variables in my command. Can someone help me ?

Thanks in advance.

BDR
  • 436
  • 2
  • 7
  • 23

1 Answers1

13

You can still place single quotes as long as the variables are intended to be initially expanded before the whole command string is executed on the shell on the remote server.

sudo ssh server "echo \"$SOMEVAR\"; awk '/pattern/{print \"hello\"}1' file > file.tmp"
konsolebox
  • 72,135
  • 12
  • 99
  • 105
  • Yes, but I wanted todo something like that : `sudo ssh $VAR "awk '/$VAR2/{print \"$VAR3\"}1' file > file.tmp"` – BDR Sep 18 '13 at 19:47
  • 1
    @BDR That would work. And probably another safer form or alternative is to send the value to awk by `-v`: `sudo ssh "$VAR" "awk -v var2=\"$VAR2\" -v var3=\"$VAR3\" '\$0 ~ var2{print var3}1' file > file.tmp"`. Just make sure that the values of those variables won't cause syntax errors. – konsolebox Sep 18 '13 at 19:50
  • thank you for your help, in fact I have a different output using `awk -v p="mypattern" -v i="insertion" '/p/{print i}1' file` OR `awk '/mypattern/{print "insertion"}1' file` Moreover the command `sudo ssh $VAR "awk '/$VAR2/{print \"$VAR3\"}1' file > file.tmp"` doesn't work, $VAR2 is not replaced... – BDR Sep 18 '13 at 20:05
  • @BDR `/p/` I think would not expand to `/mypattern/` that's why you have to use `$0 ~ p{print i}1` instead. And if quoted it is `\$0 ~ p{print i}`. – konsolebox Sep 18 '13 at 20:09
  • thanks again. I tried `$0 ~ p{print i}1` but this replaced nothing :( awk -v p="mypattern" -v i="insertion" '/$0 ~ p/{print i}1' fil – BDR Sep 18 '13 at 20:12
  • Also `'/$VAR2/{print \"$VAR3\"}1'` would remain as is and not with expanded values of `$VAR2` and `$VAR3` if you run them outside of ssh. Are you sure you're executing it remotely? If not, you don't have to quote them. Mind if you post your current whole sudo ssh command please? I mean just as a reply. – konsolebox Sep 18 '13 at 20:12
  • PERFECT ! You are write, remotely this works. Can you explain me why ? – BDR Sep 18 '13 at 20:18
  • 1
    @BDR Ssh sends the string to be executed as a new whole command to a remote shell so all you have to do is imagine how the string would like when it's being executed by the shell already. Our purpose is just to create a whole new command out of those variables and expansions, and so we do it with careful quoting. You could actually see how it would look like by doing `echo` to the ssh command before running it i.e. `echo sudo ssh ...` – konsolebox Sep 18 '13 at 20:21