Reputation: 27689
I need to escape single quotes in a variable.
ssh_command 'file=$(hostname)_server-setup_$(date +%Y-%m-%d).tar.gz && cd /var && tar -zcvf $file ini | wc -l | xargs printf \'Num files: %d, File: $file\''
I can surround the variable with double quotes, but then the internal variables will be evaluated when the variable is declared, and that's not what I want.
ssh_command "file=$(hostname)_server-setup_$(date +%Y-%m-%d).tar.gz && cd /var && tar -zcvf $file ini | wc -l | xargs printf 'Num files: %d, File: $file'"
I have now come up with this, but then $file
is just printed as $file
ssh_command (){
ssh root@host $1
}
ssh_command 'file=$(hostname)_server-setup_$(date +%Y-%m-%d).tar.gz && cd /var && tar -zcvf $file ini | wc -l | xargs printf '"'"'Num files: %d, File: $file'"'"
Num files: 61, File: $file
Upvotes: 0
Views: 1830
Reputation: 999
For this not-too-big command, I would not overcomplicate it and stick to the original double quotes, and escape just the $
which should not be expanded locally.
ssh_command "file=\$(hostname)_server-setup_$(date +%Y-%m-%d).tar.gz && cd /var && tar -zcvf \$file ini | wc -l | xargs printf 'Num files: %d, File: \$file'"
Upvotes: 3
Reputation: 2582
When sending over a complicated command over SSH (using quotes, dollar signs, semi-colons), then I prefer to Base64 encode/decode it. Here I've made base64_ssh.bash
:
#!/bin/bash
script64=$(cat script.txt | base64 -w 0)
ssh 127.0.0.1 "echo $script64 | base64 -d | bash"
In the example above, simply put the command you would like to run on the remote server in script.txt
, and then run the Bash script.
This does require one extra file, but not having to escape quotes or other special characters makes this a better solution in my opinion.
This will also work with creating functions too.
It converts the command into a Base64-encoded string which has a simpler character set (Wikipedia Base64), and these characters will never need to be escaped. Then once it's on the other side, it is decoded and then piped through to the Bash interpreter.
To make this work with your example above, put the following into script.txt
:
file=$(hostname)_server-setup_$(date +%Y-%m-%d).tar.gz && cd /var && tar -zcvf $file ini | wc -l | xargs printf "Num files: %d, File: $file"
Upvotes: 5