Escape single quotes in shell script

寵の児 提交于 2021-02-05 11:28:40

问题


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'"

update

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'"'"

output

Num files: 61, File: $file

回答1:


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'" 



回答2:


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"


来源:https://stackoverflow.com/questions/43571518/escape-single-quotes-in-shell-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!