3

I have this following shell command:

ssh user@host "df | grep /dev/ | \
awk 'BEGIN{print "DISK", "%USAGE", "STATUS"} {split($5, a, "%"); \
var="GREEN"; print $1, $5, var}' | column -t"

I need to run this over ssh but I get syntax error due to the presence of nested double and single quotes.

I tried the escape characters for before the beginning and ending of the quotes but it did not solve the problem.

However, on local system running this will give the following output:

$ df | grep /dev/ | \
awk 'BEGIN{print "DISK", "%USAGE", "STATUS"} {split($5, a, "%"); \
var="GREEN"; print $1, $5, var}' | column -t
DISK       %USAGE  STATUS
/dev/sda1  95%     GREEN
codeforester
  • 39,467
  • 16
  • 112
  • 140
Yash
  • 689
  • 4
  • 11
  • 26
  • possible duplicate of [How to escape the single quote character in a ssh / remote bash command?](http://stackoverflow.com/questions/20498599/how-to-escape-the-single-quote-character-in-a-ssh-remote-bash-command) –  May 14 '15 at 10:39
  • Note that the only thing that has to run on the remote server is the `df` command. The `grep` can run locally, although running it on the remote server reduces the amount of data sent back (not that `df` produces *that* much data). The rest you can just execute locally. – chepner May 14 '15 at 13:57

3 Answers3

8

A quoted heredoc allows you to omit the outer quotes:

ssh user@host <<'END'
df | grep /dev/ | awk 'BEGIN{print "DISK", "%USAGE", "STATUS"} {split($5, a, "%"); var="GREEN"; print $1, $5, var}' | column -t
END
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
3

This is the case where here document comes handy:

ssh -t -t user@host<<'EOF'
df | awk 'BEGIN{print "DISK", "%USAGE", "STATUS"} /dev/{split($5, a, "%"); var="GREEN"; print $1, $5, var}' | column -t
EOF
anubhava
  • 761,203
  • 64
  • 569
  • 643
1

It's much simpler to just run df | grep remotely, and process the output locally with awk:

ssh user@host 'df | grep /dev' | awk '
    BEGIN{print "DISK", "%USAGE", "STATUS"}
    {split($5, a, "%"); var="GREEN"; print $1, $5, var}' | column -t
chepner
  • 497,756
  • 71
  • 530
  • 681
  • I am integrating this with a HTTP based monitoring tool whose framework doesn't allow local processing. Well I can make it do, but I am looking for a simpler solution. – Yash May 14 '15 at 14:08
  • Yeah, its much simpler to just get the results and display. The above command is just a small part of a larger command which has a mildly complicated logic to change the values of "STATE" depending on "%used". – Yash May 14 '15 at 14:17