如何通过当前shell(zsh / bash)检测数组起始索引?

问题描述 投票:0回答:1

我们都知道Bash中的数组从零开始索引,而zsh中的数组从一开始索引。

如果我不能确定运行的环境是bash,zsh或其他东西,脚本怎么知道应该使用0或1?

预期的代码示例:

detect_array_start_index(){
  # ... how?
  echo 1
}
ARR=(ele1 ele2)
if [[ $(detect_array_start_index) = 0 ]]; then
  for (( i=$(detect_array_start_index); i < ${#ARR[@]}; i++ )); do
    echo "$i is ${ARR[$i]}"
  done
else
  for (( i=$(detect_array_start_index); i <= ${#ARR[@]}; i++ )); do
    echo "$i is ${ARR[$i]}"
  done
fi

[我有一个想法是在固定数组中找到第一个值的索引,我得到了:Get the index of a value in a Bash array,但是可接受的答案使用bash变量间接语法${!VAR[@]},在zsh中无效。

arrays bash shell indexing zsh
1个回答
1
投票

创建一个带有非空元素的数组,检查该元素是否位于索引1。例如:

detect_array_start_index() {
  local x=(y)
  case ${x[1]} in
  '') echo 0 ;;
  (y) echo 1 ;;
  esac
}
© www.soinside.com 2019 - 2024. All rights reserved.