0

When I ssh into a server and run the command, it works:

$ssh -q postgres@XXXXX
Last login: Mon Mar 12 12:30:16 2018 from 10.101.XXX.X
[postgres@pgsdba203 ~]$ df -hP | grep pgsql | awk '{ if ($5 >= 70) print $0 }'
/dev/mapper/pgvg-pg_log  9.9G  7.2G  2.2G  77% /var/lib/pgsql/data/pg_log

But not when it's part of an ssh command parameter:

$ ssh -q postgres@XXXXX "df -hP | grep pgsql | awk '{ if ($5 >= 70) print $0 }'"
awk: { if ( >= 70) print -bash }
awk:        ^ syntax error

Since the awk command is in single quotes, I'd have expected the $5 to be preserved and passed directly to server XXXXX.

EDIT: the end goal is to make the server name into a variable and call ssh from within a bash for loop.

RonJohn
  • 349
  • 8
  • 20
  • 1
    It's not in single quotes, though; the `'` are just characters in a double-quoted string, so `$5` is expanded before the string is even passed to the remote shell. – chepner Mar 12 '18 at 17:01
  • BTW -- when you're asking a question similar to many others already in the knowledgebase, it's useful to call out the near-duplicates and show how you tried to apply the advice in each and how those attempts failed. (Though as some of the duplicates include the answer you're getting from Gilles, presumably some of those attempts *wouldn't* have failed in fact). – Charles Duffy Mar 12 '18 at 17:26
  • @CharlesDuffy when typing in the subject, I looked at the existing questions that SO automatically suggested, but did not see anything relevant. – RonJohn Mar 12 '18 at 17:30

2 Answers2

1

What I would do :

ssh -q postgres@XXXXX <<'EOF'
df -hP | awk '/pgsql/ && $5 >= 70'
EOF

or in a for loop

for server in foo bar base; do
    ssh -q postgres@$server <<'EOF'
    df -hP | awk '/pgsql/ && $5 >= 70'
EOF
done
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
0

As an easy-to-define pattern, which works even when you need to pipe stdin into your remote code: Define a shell function, and tell the shell itself to emit that function's literal text substituted into the remote command:

myfunc() { df -hP | grep pgsql | awk '{ if ($5 >= 70) print $0 }'; }
ssh -q postgres@XXXX "$(declare -f myfunc); myfunc"
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441