如何执行在此使用doc的所有脚本参数?

sel*_*lf. 0 bash shell heredoc

我有一个简单的脚本,称为,可在我的整个代码库中使用sshpass

#!/bin/bash

expect << EOF
spawn $@
expect {
    "*assword" {
        send "$SSHPASS\n"
    }
}
expect eof
EOF
Run Code Online (Sandbox Code Playgroud)

我目前使用此脚本的方式是这样的-

./sshpass scp archive.tgz $SERVER:$DIR
Run Code Online (Sandbox Code Playgroud)

当SSH命令为单行代码时,这非常有效。我的问题是,当我尝试sshpass使用此处文档执行命令时。

./sshpass ssh $user@$server /bin/bash << EOF
    echo "do this..."
    echo "do that..."
    echo "and the other..."
EOF
Run Code Online (Sandbox Code Playgroud)

上面的失败是因为$@仅解析了ssh $user@$server /bin/bash

关于我如何处理SSH身份验证,请不要发表评论。当被迫使用Cygwin时,有些特定的事情(例如密钥身份验证和管理特权)根本无法工作。

Eri*_*ouf 5

Heredoc将替换您的脚本的stdin。如果您希望将其作为参数进行访问,请使用命令替换,例如

./sshpass ssh $user@$server /bin/bash $(cat << EOF
    echo "do this..."
    echo "do that..."
    echo "and the other..."
EOF
)
Run Code Online (Sandbox Code Playgroud)

尽管最终可能无法完全按照您的要求做,因为它将每个单词作为自己的位置参数传递,所以您将可以运行

ssh $user@$server echo "do this..." echo "do that..." echo "and the other..."
Run Code Online (Sandbox Code Playgroud)

它将具有第一个回显的所有其余参数作为参数。在每个命令的末尾都需要使用半冒号,并在整个内容中加上引号,因此您不必在远程进行某些操作,而在本地进行某些操作。所以我应该推荐它为:

./sshpass ssh $user@$server /bin/bash "$(cat << EOF
    echo 'do this...';
    echo 'do that...';
    echo 'and the other...'
EOF
)"
Run Code Online (Sandbox Code Playgroud)

但这仍然给我一种不安的感觉,因为很容易用这样的东西“做错事”