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 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
forloop you execute before calling ssh creates a $dir varible and your shell expands it, so you are actually executing:You should escape $ to avoid shell expansion. Try:
In this example,
$dirsis a local variable and$diris a remote variable. Your shell will replace $dirs in your command BEFORE executing ssh, so you will be really executing: