tags:

views:

62

answers:

5
for i in $LIST
do
  CFG=`ssh $i "cat log.txt|awk '{print $2}'"`
  for j in $CFG
  do
    echo $j
  done
done

Say I want to print 2nd field in the log file on a couple remote host. In above script, print $2 doesn't work. How can I fix this? Thanks.

+1  A: 

Make sure you're escaping the $2 from the shell - the ssh command you end up sending right now is something like this: ssh listvalue cat log.txt|awk '{print }'

zigdon
+1  A: 

try

for i in $LIST
do
  ssh $i "cat log.txt|awk '{print \$2}'"
done
psj
@psj, thanks, but I just edited my question again. Now backslash doesn't work. Can you please look into it again?
Stan
I'm not sure what you're trying to do there. Are you just trying to output the 2nd column of "log.txt" for each host in $LIST?
psj
A: 

Lose the cat. Its useless..

for server in $LIST
do
  ssh "$server" "awk '{print \$2}' log.txt"
don
ghostdog74
+2  A: 

Depending on the number of shell expansions and type of quoting multiple backslash escapes are needed:

awk '{ print $2 }' log.txt # none
ssh $server "awk '{ print \$2 }' log.txt" # one
CFG=`ssh $server "awk '{ print \\$2 }' log.txt"` # two
CFG=$(ssh $server "awk '{ print \$2 }' log.txt") # one (!) 

As a trick you can put a space between the dollar sign and the two to prevent all $ expansion. Awk will still glue it together:

  CFG=`ssh $i "cat log.txt|awk '{print $ 2}'"`
schot
This answer is so helpful! Thanks schot!
Stan
+1  A: 
for server in $LIST
do
   ssh "$server" 'awk "{print $2}" log.txt'
done
  • Carefully watch the location of the single-quote and the double-quote.
  • Bash tries to expand variables (words beginning with $) inside double-quote (").
  • Single-quote (') stops Bash from looking for variables inside.
  • As user131527 and psj suggested, escaping $2 with \ should also have worked (depending on how your Bash is configured).
Babil