我知道其他用户已经问过同样的问题,但是答案对我没有用。
我正在尝试通过ssh heredoc连接使用bash中的数组删除多个文件,但是不删除任何文件夹都行不通,但是,如果我使用ssh命令运行相同的命令,它将起作用。
如何修复Heredoc ssh命令?
#!/usr/bin/bash -x
DIRA="/home/developer/Documents/a"
DIRB="/home/developer/Documents/b"
DIRC="/home/developer/Documents/c"
declare -a array=($DIRA $DIRB $DIRC)
ssh -T developer@192.168.0.13 <<- EOSSH
rm -rf "${array[@]}"
EOSSH
请您参考如下方法:
考虑以下最小示例:
arr=(a b c)
cat <<EOF
printf '<%s>\n' "${arr[@]}"
EOF
输出将是
printf '<%s>\n' "a b c"
将打印
<a b c>
如果您删除引号,
printf '<%s>\n' ${arr[@]}
它扩展到
printf '<%s>\n' a b c
你得到
<a>
<b>
<c>
这就是为什么它似乎可以“解决”您的问题,但它遭受所有未引用的扩展(单词拆分,参数扩展)所带来的问题的困扰。
正如戈登在其 comment中指出的那样,这是因为
${arr[@]}立即被 shell 扩展了,但是
printf命令中的引号仅适用于该扩展的结果,导致
printf看到了一个参数。
要解决此问题,您可以将声明放入here-doc中并用引号引起来,因此shell不会展开任何内容:
cat <<'EOF'
arr=(a b c)
printf '<%s>\n' "${arr[@]}"
EOF
导致
arr=(a b c)
printf '<%s>\n' "${arr[@]}"
这会让你
<a>
<b>
<c>
适用于问题中的特定情况:
ssh -T developer@192.168.0.13 <<- 'EOSSH'
DIRA="/home/developer/Documents/a"
DIRB="/home/developer/Documents/b"
DIRC="/home/developer/Documents/c"
array=("$DIRA" "$DIRB" "$DIRC")
rm -rf "${array[@]}"
EOSSH
这时您可以直接转到
ssh -T developer@192.168.0.13 <<- 'EOSSH'
rm -rf "/home/developer/Documents/a" \
"/home/developer/Documents/b" \
"/home/developer/Documents/c"
EOSSH




