开发者

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"). Instead of having a separate ssh connection for each command, I would like to do something like:

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开发者_如何学Go remote server are all equal to the last dir value ("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.

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 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. 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. Your shell will replace $dirs in your command BEFORE executing ssh, so you will be really executing:

ssh user@server "for dir in dir1 dir2 dir3; do echo \$dir; cp some/file.txt /home/user/\$dir/; done"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜