The fact that bash is 0-indexed and zsh is 1-indexed can cause problems. For example the following will work as intended with bash, but not zsh (PS I am aware that I don't NEED to use an array for this, it's just an example):
DISK1=Samsung_SSD_850_EVO_120GB_S21SNX0H915161E
DISK2=Samsung_SSD_850_EVO_120GB_S21SNX0H915160K
DISKS=( $DISK1 $DISK2 )
mdadm --create /dev/md0 --level=mirror --raid-devices=2 "${DISKS[0]}" "${DISKS[1]}"
I was thinking I could make this shell-agnostic by writing everything relative to the index of the current shell, if there were a way to get the index of the current shell as a variable, something like this:
INDEX=$(some_function_that_returns_index)
DISK1=Samsung_SSD_850_EVO_120GB_S21SNX0H915161E
DISK2=Samsung_SSD_850_EVO_120GB_S21SNX0H915160K
DISKS=( $DISK1 $DISK2 )
echo "${DISKS[$INDEX]}" "${DISKS[$(expr $INDEX + 1)]}"
mdadm --create /dev/md0 --level=mirror --raid-devices=2 "${DISKS[$INDEX]}" "${DISKS[$(expr $INDEX + 1)]}"
Is there a way to get the index of the current shell, or alternatively get the nth array element? Ideally using just single shell commands and not a custom little script.
sh
. (cont'd)sh
may be provided by Bash, Dash or whatever, these are implementations. Any implementation should follow the specification. These shells can run portable code out of the box, but when invoked assh
they deliberately drop (some of) their extra features so the features not specified by POSIX don't interfere by chance. Any POSIX-compliant OS providessh
and you can count on it because this is the idea.