[英]How do I iterate over a local array in a remote ssh bash command
I need to perform several copy commands on a remote location (using ssh "cp blah blah2"). 我需要在远程位置执行几个复制命令(使用ssh“cp blah blah2”)。 Instead of having a separate ssh connection for each command, I would like to do something like:
我没有为每个命令分别使用ssh连接,而是想做类似的事情:
dirs=(dir1 dir2 dir3)
for dir in ${dirs[*]} ; do echo $dir; done
ssh user@server "for dir in ${dirs[*]}; do echo $dir; cp some/file.txt /home/user/$dir/; done"
But even though the first echo prints all three dirs, the echos performed on the remote server are all equal to the last dir value ("dir3"). 但即使第一个echo打印所有三个dirs,在远程服务器上执行的回声都等于最后一个dir值(“dir3”)。 I don't understand what I'm doing wrong, or why it's printing three echos (and doing three copies), when it's only using the same value.
我不明白我做错了什么,或者为什么它只使用相同的值打印三个回声(并做三个副本)。 I guess it has something to do with when the variables are expanded (locally or remotely)...
我想这与变量扩展(本地或远程)有关...
I've tried using dirs="dir1 dir2 dir3", @ instead of *, quotings, but I haven't been able to find a combination that works. 我尝试使用dirs =“dir1 dir2 dir3”,@而不是*,引用,但我找不到一个有效的组合。
Anyone have any experience with this problem? 有没有遇到过这个问题的经验? :)
:)
Cheers, Svend. 干杯,斯文德。
The for
loop you execute before calling ssh creates a $dir varible and your shell expands it, so you are actually executing: 在调用ssh之前执行的
for
循环会创建一个$ dir varible,而你的shell会扩展它,所以你实际上正在执行:
ssh user@server "for dir in dir1 dir2 dir3; do echo dir3; cp some/file.txt /home/user/dir3/; done"
You should escape $ to avoid shell expansion. 你应该逃避$以避免shell扩展。 Try:
尝试:
dirs="dir1 dir2 dir3"
ssh user@server "for dir in $dirs ; do echo \$dir; cp some/file.txt /home/user/\$dir/; done"
In this example, $dirs
is a local variable and $dir
is a remote variable. 在此示例中,
$dirs
是局部变量, $dir
是远程变量。 Your shell will replace $dirs in your command BEFORE executing ssh, so you will be really executing: 在执行ssh之前,你的shell将在你的命令中替换$ dirs,所以你将真正执行:
ssh user@server "for dir in dir1 dir2 dir3; do echo \$dir; cp some/file.txt /home/user/\$dir/; done"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.