简体   繁体   中英

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.

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.

初看起来,我会说你错过了循环中的最后done

ssh username@hostmachine 'for((i = 0 ; i < $num ; i++ )); do ln -sf ${array1[$i]} ${array2[$i]}; done'

The variable substitution isn't happening insside single quotes. Try double quotes instead:

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM