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
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'"
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.
The way it works, is 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"