Issue
I need to pipe multiple ssh commands in order to run commands on a remote machine. The commands are working fine with a single ssh but not after piping ssh. E.g
ssh [email protected] "a=hello ; echo \$a"
return hello but
ssh [email protected] ssh [email protected]"a=hello ; echo \$a"
produces no output.
Similarly:
ssh [email protected] "mountedDir=\$(df \tmp | grep -vi filesystem | rev | cut -d ' ' -f 1); mount | grep -w \$mountedDir"
Is working fine producing the following output :
/dev/sda2 on / type xfs (rw,relatime,attr2,inode64,noquota)
but
ssh [email protected] ssh [email protected] "mountedDir=\$(df \tmp | grep -vi filesystem | rev | cut -d ' ' -f 1); mount | grep -w \$mountedDir"
is throwing the following error:
Usage: grep [OPTION]... PATTERN [FILE]...
Try 'grep --help' for more information.
Note: Passwordless ssh is established from my machine to remotemachine1.com and from remotemachine1.com to remotemachine2.com
Solution
It finally worked after I added multiple escape characters
ssh [email protected] " ssh [email protected] \" a=hello ;echo \\\$a \" "
And
ssh [email protected] " ssh [email protected] \" mountedDir=\\\$(df /var | grep -vi filesystem | rev | cut -d ' ' -f 1); mount | grep -w \\\$mountedDir | grep -vi 'noexec' \" "
Answered By - Vatsal Prakash Answer Checked By - David Marino (WPSolving Volunteer)