Issue
We all know arrays in Bash are indexed from zero, and in zsh are indexed from one.
How can the script know it should use 0 or 1 if I can't ensure the running environment is bash, zsh or something else?
Expected code sample:
#!/bin/sh
detect_array_start_index(){
# ... how?
echo 1
}
ARR=(ele1 ele2)
startIndex=$(detect_array_start_index) # 0 or 1
for (( i=${startIndex}; i < ${#ARR[@]} + $startIndex; i++ )); do
echo "$i is ${ARR[$i]}"
done
I have a idea is find the index of the first value in a fixed array, I got this: Get the index of a value in a Bash array, but the accepted answer use bash variable indirection syntax ${!VAR[@]}
, which is invalid in zsh.
Solution
Check the index 1 element of a two element array:
detect_array_start_index() {
local x=(1 0)
echo ${x[1]}
}
Answered By - okapi Answer Checked By - Candace Johnson (WPSolving Volunteer)