簡體   English   中英

ssh 命令中的轉義單引號

[英]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 不會將它們擴展為值。

何時在 shell 變量周圍加上引號?

請嘗試以下方法:

#!/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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM