I am a bit new to the bash scripting. So please bear with me. I am trying to create a table and assign the values in for loop like this:
packages=("foo" "bar" "foobar")
packageMap=()
function test() {
i=0;
for package in "${packages[@]}"
do
echo $i
packageMap[$package]=$i
i=$(expr $i + 1)
done
}
test
echo the first value is ${packageMap["foo"]}
The output for this is:
0
1
2
the first value is 2
While my expected output is:
0
1
2
the first value is 0
So basically the variable's reference is being assigned to this rather than the value. How to solve this?
My bash version:
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin16)
TIA
i=$(( i + 1 ))is much more efficient thani=$(expr $i + 1), as$( )needs to fork off a child process, andexpris implemented with an external command --/bin/expr-- not part of the shell. The$(( ))form has been present in the POSIX sh standard since its initial publication in 1991, so there's also no concern about portability.i=$(( i + 1 ))over((i++))? I find the latter easier to read and to type.((i++))can (depending on the interpreter version) cause your script to exit when you're usingset -e.((++i))is less prone to that issue (would only happen wheniis initially negative).