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

标签 arrays bash shell indexing zsh

我们都知道 Bash 中的数组是从 0 开始索引的,而在 zsh 中是从 1 开始索引的。

如果我不能确保运行环境是 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 中无效。

最佳答案

检查二元素数组的索引 1 元素:

detect_array_start_index() {
  local x=(1 0)                                                   
  echo ${x[1]}
}

关于arrays - 如何通过当前 shell (zsh/bash) 检测数组开始索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62192252/

相关文章:

ios - Firebase 数据库和 Swift : Save location data in an array

Bash:用新行替换空格并在前面加上破折号

Linux Bash - 将错误重定向到文件

linux - 从 Linux Bash Shell 配置 NIC

python - 如何使用 shell 脚本(和 makefile?)执行 python 程序

php - 从 PHP 中的数组中删除空的 stdclass 对象

php - 显示每个卧室数量的图标(酒店网站)php

arrays - 三维或三维以上的数组有哪些有趣/实际的用途?

连续管道输入

android - 如何使用 shell 命令启动 Genymotion 设备?