arrays - 如何通过当前 shell(zsh/bash)检测数组起始索引?
问题描述
我们都知道 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 中是无效的。
解决方案
检查二元素数组的索引 1 元素:
detect_array_start_index() {
local x=(1 0)
echo ${x[1]}
}
推荐阅读
- python - 当我尝试在 conda 环境中运行 python2 文件时,g++ 不支持“-ffast-math -march=native”参数
- javascript - Onclick 图像按钮 - 逻辑没有意义
- python - 如何在不同文件中保存和加载 Sklearn 模型
- node.js - 为什么 NodeJS 中没有删除特定的数组?
- firebase - 使用firestore向前和向后跳转分页
- rdf - 如何为与它们相关的另一个类的每个实例都不同的实例创建计数属性?
- reactjs - ReactJS:动态更改 html/jsx 元素
- r - 在数据帧上使用 dplyr::union_all 而非其他行绑定方法的原因
- javascript - Discord BOT 对命令无响应且无控制台输出 (discord.js)
- python - 将列标签添加到条形图(Python-matplotlib)