linux - 变量作为 bash 数组索引?

标签 linux bash

#!/bin/bash

set -x

array_counter=0
array_value=1

array=(0 0 0)

for number in ${array[@]}
do
    array[$array_counter]="$array_value"
    array_counter=$(($array_counter + 1))
done

当运行上面的脚本时,我得到以下调试输出:

+ array_counter=0
+ array_value=1
+ array=(0 0 0)
+ for number in '${array[@]}'
+ array[$array_counter]=1
+ array_counter=1
+ for number in '${array[@]}'
+ array[$array_counter]=1
+ array_counter=2
+ for number in '${array[@]}'
+ array[$array_counter]=1
+ array_counter=3

为什么变量 $array_counter 在 array[] 中用作索引时不展开?

最佳答案

Bash 似乎对变量作为数组索引非常满意:

$ array=(a b c)
$ arrayindex=2
$ echo ${array[$arrayindex]}
c
$ array[$arrayindex]=MONKEY
$ echo ${array[$arrayindex]}
MONKEY

关于linux - 变量作为 bash 数组索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11856132/

相关文章:

linux - 从 shell 脚本打开 gnome-terminal 并保持窗口打开

python - source ~/.profile 命令抛出奇怪的错误

linux - 如何剥离grep的输出?

linux - Linux 中的 XINERAMA&FAKEEXTN

linux - 在多宿主 Linux 服务器中收听多播的问题

linux - 远程执行需要输入的 bash 脚本

php - 无法以完全权限运行 shell 脚本 (UNIX)

html - ubuntu 中的 css @font-face 不起作用

bash - 删除大型单词列表中重复项的最快方法?

linux - 检查参数是否是 bash shell 中的有效日期