0

I am working in Bash shell, Linux OS. I have the following for loop:

for ((i=0;i<${#listModels[@]};i++))
do
var=${listVersion[$i]}
if [ ${!var} ]
then
    export MY_LIBRARY_PATH=$MY_LIBRARY_PATH:$ROOT_PATH/${listModels[$i]}/${listModels[$i]}_${!var}
else
    echo ">>>> No ${listModels[$i]} version! <<<<"
fi
done

Before this, I have the following in the script:

listModels=(model1
model2
model3)

listVersion=(MODEL1
MODEL2
MODEL3)

The concept is MODEL1,MODEL2 and MODEL3 keep changing every now and then, for eg it becomes MODEL1.1,MODEL2.2,.. And I expect the script to modify my path everytime the listVersion values change. But could anybody explain how exactly the for loop functions (especially [@] and [$i] stuff). I am new to Bash and I know only the basic commands. Thanks in advance!

1 Answer 1

3

As documented in man bash, ${#array[@]} returns the number of elements in the array. Similarly, ${array[$i]} (better written as ${array[i]}) returns the $i-th element of the array.

#! /bin/bash
array=( a b c )
echo Size: ${#array[@]}
echo First: ${array[0]}
echo Second: ${array[1]}
echo Last: ${array[-1]}  # Negative index counts from the right!
Sign up to request clarification or add additional context in comments.

2 Comments

IIRC negative indexing is allowed from bash 4.2
The expression within the if statement if [ ${!var} ] means i-th element does not exist?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.