'How to detect array start index by current shells (zsh/bash)?
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 1:[1]
Check the index 1 element of a two element array:
detect_array_start_index() {
local x=(1 0)
echo ${x[1]}
}
Solution 2:[2]
You can set the KSH_ARRAYS
option in zsh
to force array indexing to start at 0.
{ setopt KSH_ARRAYS || : ; } 2> /dev/null
ARR=(ele1 ele2)
for ((i=0; i < ${#ARR[@]}; i++ )); do
echo "$i is ${ARR[$i]}"
done
The command group and redirection allows the entire command to act as a no-op if executed from bash
. The preceding code produces the same output in zsh
and bash
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | okapi |
Solution 2 | chepner |