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.

1
  • I tried replacing array with a varible and same observation Commented Nov 20, 2019 at 13:03

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Your explanation is good. You could also add a sample of the correct call of fill_id in the condition.
3

Just don't execute the function in a subshell.

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

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.