Search code examples
arraysbashif-statementsubshell

Bash array fails to populate if function is executed as if condition


I have a function which populates a global bash array

#!/bin/bash

# Array to store debugger IDs
ID=()

fill_id()
{
    for i in 1 2 3 4 5
    do
        ID+=( $i )
    done

    echo "fill_ids      - entries in ID: ${#ID[*]}"
}

If function is called directly, array gets populated and entry count is printed as 5

fill_id
echo "main          - entries in ID: ${#ID[*]}"

Output

fill_ids      - entries in ID: 5
main          - entries in ID: 5

But if function is called in if condition then entry count is printing as 0

if (fill_id)
then
    echo "main          - entries in ID: ${#ID[*]}"
fi

Output

fill_ids      - entries in ID: 5
main          - entries in ID: 0

Return value of fill_fd is not affecting anything either.


Solution

  • you are executing function in a subshell so it changes variable of child shell which is not visible in parent shell culprit is "()" you can debug it with printing shell id - see bellow:

    #!/bin/bash
    
    # Array to store debugger IDs
    ID=()
    
    echo $BASHPID
    fill_id()
    {
        for i in 1 2 3 4 5
        do
            ID+=( $i )
        done
    echo $BASHPID
        echo "fill_ids      - entries in ID: ${#ID[*]}"
    }
    
    
    if  (fill_id)
    then
        echo "main          - entries in ID: ${#ID[*]}"
    fi
    

    when you call function directly (without subshell) then it properly changes your variable.

    Like this:

    if fill_id
    then
        echo "main          - entries in ID: ${#ID[*]}"
    fi