Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does this bash script work even with the typo

So I have this bash script to find the Fibonacci sequence for n terms. Its definitely not great code, but I notices that it still works with a typo

read -p "Enter which term of fibo seq to find: " n

table=(1 1)

for i in $(seq 0 $(($n - 1)) )
do
    if [[ -z ${table[$i]} ]]; then
        a1=$(( $i - 1 ))
        a2=$(( $I - 2 ))
        val=$(( ${table[$a1]} + ${table[$a2]} ))

        table+=($val)
    fi
done

echo ${table[@]}

inside the if statement evaluating the expression for a2, there is a capital ‘I’ instead of ‘i’. My understanding is that shellscript is case sensitive but I’m new to it. So can anyone explain why this works?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

a2 will always be -2. Starting with bash 4.2, you can index into an array using negative indices, much like in Python. So with or without the typo, you are always accessing the second last element in the array.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading