How to print a specific column with awk on a remote ssh session?

You're hitting a quoting problem; the $5 is being interpreted at the wrong time. There are at least two solutions:

  1. Put a \ before the $; e.g.

    /usr/bin/ssh -i /path/to/key user@server "df -h | grep /dev/root | awk '{print \$5}'"

  2. Run the df remotely but the grep and awk locally. e.g.

    /usr/bin/ssh -i /path/to/key user@server df -h | grep /dev/root | awk '{print $5}'

FWIW, I'd run a version of the second option but merging grep and awk

/usr/bin/ssh -i /path/to/key user@server df -h | awk '/\/dev\/root/ {print $5}'

This should work:

/usr/bin/ssh -i /path/to/key user@server "df -h | grep /dev/root | awk '{print \$5}'"

Notice the \ included before the $. Without this, the local shell will expand the empty variable $5 and send that to the remote server. Essentially, printing the entire line.


For completeness, another way is to use the fact $n in awk isn't a special case of $variable syntax like shell, but instead the $ operator applied to an integer expression:

(ssh key&remote) "df -h | grep /dev/root | awk '{print $ 5}'"

or combined as

(ssh key&remote) "df -h | awk '/\\/dev\\/root/ {print $ 5}'"
# can use [/] instead of ugly \\/ in gawk, but maybe not others

or maybe better as a variable

(ssh key&remote) "df -h | awk -vm=/dev/root '$ 0 ~ m {print $ 5}'"

But personally I'd go with Stephen Harris' preference to run the awk locally.

Tags:

Ssh

Awk