I need to get result of which process is using most swap space on a remote server. I am using below command which works fine if I log on to remote and run it, but it gives no output if I run it by using ssh to remote. I need to use ssh as I'll be doing this for multiple servers in a script

ssh someserver "for file in /proc/*/status; do awk '/VmSwap|Name/{printf $2 " " $3} END{print ""}' $file; done | sort -k 2 -n -r | head -1 | awk '{print $1}'"

I also tried using suggestions from previous questions on ths portal to enclose complete command in single quotes and awk in double quotes but that errors out for me as the double quote in printf statement is interpreted as closing of outer double quote of awk.

  • Your life will be easier if you minimize what you do while on the remote machine. ssh someserver 'cat /proc/*/status' | awk 'foo' will remove any quoting issues compared to ssh someserver "awk 'foo' /proc/*/status" or similar (you don't need a loop either way btw).
    – Ed Morton
    Mar 19, 2021 at 16:47

1 Answer 1


The problem is the quoting.

Use echo instead of ssh to see what would be transmitted to the ssh server:

$ echo "for file in /proc/*/status; do awk '/VmSwap|Name/{printf $2 " " $3} END{print ""}' $file; done | sort -k 2 -n -r | head -1 | awk '{print $1}'"
for file in /proc/*/status; do awk '/VmSwap|Name/{printf    } END{print }' ; done | sort -k 2 -n -r | head -1 | awk '{print }'

You see that the shell expands $1, $2 and $3. In an interactive shell, these are most likely empty strings. It might be enough to replace $ with \$, I didn't test it.

In general I prefer to send the commands on stdin, obviously this doesn't work if you need stdin. An additional advantage is that you can format it on multiple lines.

cat << 'EOF' |
for file in /proc/*/status; do
  awk '/VmSwap|Name/{printf $2 " " $3} END{print ""}' $file
done | sort -k 2 -n -r | head -1 | awk '{print $1}'
ssh someserver /bin/sh
  • Is the VmSize always reported in the same unit?
    – Kusalananda
    Mar 19, 2021 at 9:38
  • I didnt get the echo part as I have to run this on a remote linux machine and ssh was the way I was using to connect. stdin thing works though.
    – STJ
    Mar 19, 2021 at 13:35
  • The echo part will show you the command that would be transmitted to the ssh server. If the output from echo is garbled, the command to the ssh server is garbled, too. I edited the answer, I hope it makes more sense now.
    – RalfFriedl
    Mar 20, 2021 at 7:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .