Similar to Why doesn't echo called as /bin/sh -c echo foo output anything? but using ssh
.
Why doesn't this output anything:
ssh localhost sh -c 'echo "0=$0 1=$1"' arg1 arg2 arg3
But if I change it to
ssh localhost sh -c 'true; echo "0=$0 1=$1"' arg1 arg2 arg3
# Output is
0=bash 1= arg1 arg2 arg3
I see behavior that implies the echo command is being run but the way the variable substitution is working is not as expected. See https://unix.stackexchange.com/a/253424/119816
Running without ssh works as expected
Same as above but removing the ssh command
sh -c 'echo "0=$0 1=$1"' arg1 arg2 arg3
# Output is
0=arg1 1=arg2
Adding true gives same output
sh -c 'true; echo "0=$0 1=$1"' arg1 arg2 arg3
0=arg1 1=arg2
I'm trying copy a root accessible file from one system to another
I'm trying to get an ssh command working to copy a root file to another system. The command I'm trying is:
file=/etc/hosts
set -x
ssh host1 sudo cat $file | ssh host2 sudo sh -c 'exec cat "$0"' $file
# Output is
+ ssh host2 sudo sh -c 'exec cat > "$0"' /etc/hosts
+ ssh host1 sudo cat /etc/hosts
bash: : No such file or directory
This looks OK to me, and I'm not sure how else to troubleshoot.
My solution
My solution is to fall back to what I've used before
ssh host1 sudo cat $file | ssh host2 sudo tee $file > /dev/null
The above works.
Searching for a solution
I've had this problem and asked the question:
Other's have had problems/questions with sh -c
command:
But there must be a subtlety that occurs when using ssh which results in an additional shell evaluation.