Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SSH command option with bash for loop

I want to symbolically link two arrays' elements. For example, array1 = (AAA BBB CCC DDD), array2 = (001 002 003 004), 001->AAA, 002->BBB, 003->CCC and 004->DDD.

Here is the shell script I wrote, but it doesn't work, and I couldn't figure out where is wrong.

declare -a array1=(AAA BBB CCC DDD)
declare -a array2=(001 002 003 004)
num = ${#array1[@]}
ssh username@hostmachine 'for((i = 0 ; i < $num ; i++ )); do ln -sf ${array1[$i]} ${array2[$i]}; done' 

Can anyone give me some hints/advice? Thank you in advance.

like image 709
user1846268 Avatar asked Feb 22 '26 08:02

user1846268


2 Answers

You should include all your bash code inside the parameter to ssh, like this:

ssh username@hostmachine 'declare -a array1=(AAA BBB CCC DDD); declare -a array2=(001 002 003 004); num = ${#array1[@]}; for((i = 0 ; i < $num ; i++ )); do ln -sf ${array1[$i]} ${array2[$i]}; done'

because otherwise the ssh bash code won't get access to your previously defined arrays, because they were defined in your computer not in the ssh one.

like image 73
Nelson Avatar answered Feb 24 '26 20:02

Nelson


At a first look, I would say you're missing a final done in your loop:

ssh username@hostmachine 'for((i = 0 ; i < $num ; i++ )); do ln -sf ${array1[$i]} ${array2[$i]}; done'
like image 21
Olaf Dietsche Avatar answered Feb 24 '26 20:02

Olaf Dietsche