Reputation: 45
I have the following Bash code:
while read -a line; do
if [[ line[2] == $2 ]]; then
version[n]=${line[1]}
let n++
fi
done <"$file"
I know for a fact that there's a line in the file which is suppose to satisfy the if statement. I am not comparing numbers but strings so it's not the problem. What's the problem with my if statement?
Upvotes: 0
Views: 97
Reputation: 81042
You need to use ${line[2]}
there.
[[
doesn't automatically expand bare words like ((
does.
See:
$ line=(a b c)
+ line=(a b c)
$ [[ line[1] = a ]]; echo $?
+ [[ line[1] = a ]]
+ echo 1
1
$ [[ ${line[1]} = a ]]; echo $?
+ [[ b = a ]]
+ echo 1
1
$ [[ ${line[0]} = a ]]; echo $?
+ [[ a = a ]]
+ echo 0
0
$ line=(0 1 2)
+ line=(0 1 2)
$ (( line[1] == 1 )); echo $?
+ (( line[1] == 1 ))
+ echo 0
0
$ (( line[2] == 1 )); echo $?
+ (( line[2] == 1 ))
+ echo 1
1
[[` does do bare word expansion when used with integer operations. However given how this actually works I don't like that behavior at all and do not understand why it works the way it does.
Upvotes: 5