为了开始分布式计算,我编写了一个运行脚本,它使用ssh
登录到一台远程计算机,并启动一个从标准输入读取的脚本.但是,此运行脚本需要将用户提供的参数从$@
正确传输到远程计算机.然而,我注意到这些论点没有被正确传达.
假设远程机器应该执行的脚本task.sh
是
i=0
for p in "$@"; do
echo "#${i}: ${p}"
i=$((i+1))
done
此脚本简单地迭代参数并逐行打印它们,例如,
$ bash task.sh hello world 'in one line'
#0: hello
#1: world
#2: in one line
我的简化运行脚本run.sh
现在如下所示:
ssh user@remote.example.com "bash -s $@" < task.sh
但是,这将打印以下内容:
$ bash run.sh hello world 'in one line'
#0: hello
#1: world
#2: in
#3: one
#4: line
当我引用$@
与'
,即.
ssh user@remote.example.com "bash -s '$@'" < task.sh
打印的内容如下:
$ bash run.sh hello world 'in one line'
#0: hello world in one line
也许,当我在run.sh
中使用一个数组时,它是有效的?
ARGS=(bash -s "$@")
ssh user@remote.example.com "${ARGS[@]}" < task.sh
不,它还可以打印多行'in one line'
.
在${ARGS[@]}
左右添加额外的单引号会使ssh
将其解释为单个命令和报告:bash: bash -s hello world in one line: command not found
.
那么,如何正确地将参数传递给ssh
,以便正确地拆分它们呢?我想,它可能可以与环境变量一起工作,但我也可以让它在没有环境变量的情况下工作吗?