1

I am using the variable "i" three times in the following simple bash script which essentially generates random numbers which are not there in an array. Can someone help me understand the scope of each of these variables here?

timestamp="9"
researchArea="5"
numberOfDimensions="8"


timeStampToInjectArray=()
dimensionToTamperArray=()
for((i=0;i<$numberOfDimensions;i++))
do     
    echo $i
    while : ;
    do

        timeStampToInject=$(shuf -i 0-$timestamp -n 1)
        dimensionToTamper=$(shuf -i 1-$researchArea -n 1)
        flag=0
        for((i=0;i<${#timeStampToInjectArray[@]};i++))
        do
            echo $i
            if [ "${timeStampToInjectArray[i]}" -eq "$timeStampToInject" ] && [ "${dimensionToTamperArray[i]}" -eq "$dimensionToTamper" ]; then
            flag=1
            fi
        done
        if [ "$flag" -eq "0" ]; then
            break
        fi

    done
    timeStampToInjectArray+=("$timeStampToInject")
    dimensionToTamperArray+=("$dimensionToTamper")
    echo $timeStampToInject,$dimensionToTamper
done

1 Answer 1

2

If you are used to languages like C, C++, Java, etc. then you will expect the counter in a computed for loop to have local scope. No, not in Bash. There is only one variable i:

i='hello sailor'

for ((i=0; i < 5; i++))
do
    echo "outer:$i"
    for ((i=0; i < 5; i++))
    do
        echo "inner:$i"
    done
done

echo "final:$i"

Gives:

outer:0
inner:0
inner:1
inner:2
inner:3
inner:4
final:6

Bash (like Python) doesn't have block scope in conditionals. It has local scope within functions, and if you want to build structured code in bash then you have to go down that route.

For example:

loop_n_times() {

    local i           # <<< locally scoped 
    local limit=$1    # <<< locally scoped

    for ((i=0; i < $limit; i++))
    do
        echo "function:$i"
    done
}

i='hello sailor'

for ((i=0; i < 5; i++))
do
    echo "outer:$i"
    loop_n_times 5
done

echo "final:$i"

Gives:

outer:0
function:0
function:1
function:2
function:3
function:4
outer:1
function:0
function:1
function:2
function:3
function:4
outer:2
function:0
function:1
function:2
function:3
function:4
outer:3
function:0
function:1
function:2
function:3
function:4
outer:4
function:0
function:1
function:2
function:3
function:4
final:5

Alternatively, don't use the same variable name for different things - which is probably a good idea anyway.

Sign up to request clarification or add additional context in comments.

Comments

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.