0

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.

Shubham
  • 628
  • 1
  • 9
  • 19

2 Answers2

4

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
Léa Gris
  • 17,497
  • 4
  • 32
  • 41
Maxim Sagaydachny
  • 2,098
  • 3
  • 11
  • 22
  • 1
    Your explanation is good. You could also add a sample of the correct call of `fill_id` in the condition. – Léa Gris Nov 20 '19 at 13:43
3

Just don't execute the function in a subshell.

if fill_id
then
    echo "main          - entries in ID: ${#ID[*]}"
fi
KamilCuk
  • 120,984
  • 8
  • 59
  • 111