for loop doesn't work when "{0..$var}" is used [duplicate]
Simple problem but I don't know how to fix it. Here's the code:
missing_filters=('Sort key' 'Page' 'Pagesize' 'Sort direction')
for level in {0..$((${#missing_filters[@]}-1))}
do
echo "${#missing_filters[$level]}^|^${missing_filters[$level]}"
done | column -tes "^"
It should show every element of the array with 1-4 before it like this:
1 | Sort key
2 | Page
3 | Pagesize
4 | Sort direction
However, I get the error ./advancedplexapi.sh: line 4608: {0..3}: syntax error: operand expected (error token is "{0..3}")
. I find this strange as the error shows exactly how I want the shell to interpret it (that being {0..3}
). I did nothing wrong because otherwise the shell wouldn't give me the correct output in the error. Why doesn't it work? And ofcourse how can I fix this?
Solution 1:
It is not working as expected, because brace expansion is done before variable substitution.
You could use seq
or a for
-loop instead:
for level in $(seq 0 $((${#missing_filters[@]}-1))); ...
or
for (( level=0;level<="$((${#missing_filters[@]}-1))";level++ )); ...
For more details, see this answer to another question.
Also "${#missing_filters[$level]}"
will not give 1 2 3 4
, but expand to the number of characters in each value --> 8 4 8 14
. Better use $((level+1))
.
However, you could more easily loop the array keys:
for k in "${!missing_filters[@]}"; do
printf '%s | %s\n' "$((k+1))" "${missing_filters[$k]}"
done