0

I have the following command which I trying to execute in a custom bash script in Linux:

CMD="gnome-terminal" 
CMD="$CMD --tab -e \"ssh root@172.16.17.4 'iperf -c 10.0.0.7 -t 10 -i 0.1 -f m | awk '{print $7}' > results.txt;tail -n1 results.txt'\""
eval ${CMD}

It seems that bash is getting confused during the execution because of the single quotations after the grep command for matching a regular expression. So my question who can I inform the bash that those single quotations are part of the command to be executed?

codeforester
  • 39,467
  • 16
  • 112
  • 140
  • The single quotes that are supposed to enclose the `ssh` command are broken by the `awk`'s ones. I'm sure there is a better way than using eval, I'm not even sure what it is supposed to help with there. – Aaron May 05 '17 at 17:33
  • why not write a pipe in its traditional form? – RomanPerekhrest May 05 '17 at 17:35
  • I think you could avoid your immediate problem by changing your `awk '{print $7}'` into `cut -f7` (or something close), but I'm sure you'll be running into other problems with such a script – Aaron May 05 '17 at 17:37
  • @Aaron `cut -f7` does not work. @RomanPerekhrest what do you mean by traditional form of pipe? –  May 05 '17 at 17:40
  • 1
    Storing a command in a variable like this can cause many sorts of trouble. See [BashFAQ #50: I'm trying to put a command in a variable, but the complex cases always fail!](http://mywiki.wooledge.org/BashFAQ/050). You'd remove one layer of quoting confusion by using a function instead. – Gordon Davisson May 05 '17 at 17:41
  • *(or something close)* `echo "1 2 3 4 5 6 7 8 9" | cut -d' ' -f7` will only print 7. Now I don't know your field separators, you may still have to adapt it – Aaron May 05 '17 at 17:41
  • @Aaron I have irregular field separator that's why I am using `awk` with regular expression –  May 05 '17 at 17:42
  • I'm actively editing the list of duplicate questions, but really, I agree with Gordon that [BashFAQ #50](http://mywiki.wooledge.org/BashFAQ/050) is the pertinent canonical reference here. – Charles Duffy May 05 '17 at 17:43
  • And btw, inasmuch as you're quoting a command to be passed to `gnome-terminal -e`, and quoting a command *within that* to be passed over `ssh`, you **really** should let the shell handle the multi-layered quoting for you. – Charles Duffy May 05 '17 at 17:48
  • See http://stackoverflow.com/questions/42537239/what-difference-does-ssh-command-quoting-make/42537289 -- the same technique used there to create `rmt_cmd` can also be used to form an argument to be passed as an argument with `gnome-terminal --tab -e "$cmd"`. (This would be two passes, then -- one for ssh, one for gnome-terminal). – Charles Duffy May 05 '17 at 17:50

0 Answers0