如何在Bash中遍历数组?

22 浏览
0 Comments

如何在Bash中遍历数组?

这个问题已经有答案了:

如何在Bash中循环遍历一个字符串数组?

我用Bash写了一些脚本,但它不起作用。有人能帮我吗?

我在此提供脚本:

#!/bin/bash
declare -a array=("red" "blue" "green" "yellow")
for (( i=0; i<${array[@]}; i++));
do
        echo "items: $i"
done

我想要循环遍历数组。

因为每当我这样做时,我会得到一个错误,说:arr1.sh: 2: Syntax error: \"(\" unexpected

admin 更改状态以发布 2023年5月20日
0
0 Comments

试试这个:

$ cat iterate_array.sh 
#!/bin/bash
declare -a array=("red" "blue" "green" "yellow")
for  i in ${!array[@]}; do
        echo ${array[$i]}
done
$ ./iterate_array.sh 
red
blue
green
yellow

这就是你想要的吗?

0