I've searched and searched on here for an answer, and I think the combination of being a noob at bash, not knowing the right way to do this, and not searching for the right keywords has meant I can't quite get over the last hurdle.
I'm writing a basic bash script to create config lines into a file based on the contents of a comma separated array variable. It works perfectly for single variables, but when I try and combine the two array variables it doesn't quite work. I've tried looping within the loop and that just creates the lines one after the other when I want it to loop with the other 5 lines it creates.
The two variables have the same number of iterations. Eg:
and I want to pass them together into the loop:
Here is the code extract:
arr1=$(echo $sites | tr "," "\n")
arr2=$(echo $mastermacs | tr "," "\n")
IFS="," read -a arr1 <<< "$sites"
IFS="," read -a arr2 <<< "$mastermacs"
for y in "${!arr1[@]}"; do
# for x in "${arr2[@]}"; do
n=$(($n+1))
echo "config flexconnect group ${arr1[y]} add"$'\r' >> Flex-cfg.txt
echo "config flexconnect group ${arr1[y]} ap add ${arr2[x]} "$'\r' >> Flex-cfg.txt
echo "config flexconnect group ${arr1[y]} predownload master ${arr1[y]}_AP01"$'\r' >> Flex-cfg.txt
echo "config flexconnect group ${arr1[y]} predownload enable"$'\r' >> Flex-cfg.txt
echo "config flexconnect group ${arr1[y]} predownload start primary"$'\r' >> Flex-cfg.txt
# done
done
It's this line in particular that I'm trying to iterate with 2 values (incidentally I've used it with just $y
and $x
as well, I've just been tinkering):
echo "config flexconnect group ${arr1[y]} ap add ${arr2[x]} "$'\r' >> Flex-cfg.txt
But as it stands it just puts the first one each time. Value Y is a name, and value X is a MAC Address.
I'm either very close or completely and utterly wrong. So could do with some kind help!
IFS=, read -a sz <<< "$sites"
IFS=, read -a mz <<< "$mastermacs"
fx='config flexconnect group'
for x in ${!sz[*]}
do
echo "$fx ${sz[x]} add"
echo "$fx ${sz[x]} ap add ${mz[x]}"
echo "$fx ${sz[x]} predownload master ${sz[x]}_AP01"
echo "$fx ${sz[x]} predownload enable"
echo "$fx ${sz[x]} predownload start primary"
echo
done
Don’t use arr1
. You can get lost in the code pretty quick if your variable
names have no meaning
I added extra empty echo
, to help readability in the output