我知道其他用户已经问过同样的问题,但是答案对我没有用。
我正在尝试通过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
关于linux - 如何使用ssh heredoc在bash中删除多个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64281318/