Arrays – SSH command option with bash for loop

SSH command option with bash for loop… here is a solution to the problem.

SSH command option with bash for loop

I want to symbolically link the elements of two arrays. For example, array1 = (AAA BBB CCC DDD), ARRAY2 = (001 002 003 004), 001->AAA, 002->BBB, 003->CCC, AND 004 ->DDD

Below is the shell script I wrote, but no, I can’t think of anything 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 tips/advice? Thank you in advance.

Solution

You should include all bash code in the parameters of ssh as follows:

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'

Otherwise, the ssh

bash code will not be able to access the arrays you defined earlier because they are defined in your computer, not in your ssh machine.

Related Problems and Solutions