![](/img/trans.png)
[英]How to escape the single quote character in an ssh / remote bash command?
[英]Escape single quote in ssh command
我正在嘗試使用 ssh 發送 sed 命令。
這是我的腳本:
#!/bin/bash
IP_PUBLIC="192.168.0.1"
from="DB_HOST='my_host'"
to="DB_HOST='192.168.0.2'"
ssh -oStrictHostKeyChecking=no root@"$IP_PUBLIC" '
sed -i "s/'"$from'"/'"$to'"/g" /path/to/file;
'
這給我帶來了以下錯誤:
test: line 9: unexpected EOF while looking for matching `''
test: line 10: syntax error: unexpected end of file
我也試過
#!/bin/bash
IP_PUBLIC="192.168.0.1"
ssh -oStrictHostKeyChecking=no root@"$IP_PUBLIC" '
sed -i "s/DB_HOST=\'my_host\'/DB_HOST=\'192.168.0.2\'/g" /path/to/file;
'
我得到了同樣的錯誤
文件內容
#!/bin/bash
DB_HOST='my_host'
需要
#!/bin/bash
DB_HOST='192.168.0.2'
不要考慮如何雙重轉義,而是使用標准輸入並使用 bash declare -p
和函數傳遞實際變量declare -f
。
IP_PUBLIC="192.168.0.1"
from="DB_HOST='my_host'"
to="DB_HOST='192.168.0.2'"
work() {
sed -i "s/$from/$to/g" /path/to/file;
}
ssh -oStrictHostKeyChecking=no root@"$IP_PUBLIC" bash -s <<EOF
$(declare -p from to) # hand-pick transfer variable values
$(declare -f work) # hand-pick transfer code
# everything is properly quoted, as it would be on localhost
work # execute the function.
EOF
由於變量$from
和$to
是單引號字符串( '
)的一部分,bash 不會將它們擴展為值。
請嘗試以下方法:
#!/bin/bash
IP_PUBLIC="192.168.0.1"
from="DB_HOST='my_host'"
to="DB_HOST='192.168.0.2'"
ssh -oStrictHostKeyChecking=no root@"$IP_PUBLIC" "sed -i \"s/${from}/${to}/g\" /path/to/file;"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.