如何在 bash 中使用数组?

ans*_*ker 3 bash

我正在 16.04 中尝试此操作,但它不起作用。摘自: https: //stackoverflow.com/a/8880633/2771043

编辑:显然,如果您将其复制并粘贴到终端而不是脚本文件上,这将有效。如何让它在 .sh 文件上以相同的方式工作?

declare -a arr=("element1" "element2" "element3")

for i in "${arr[@]}"
do
   echo "$i"
done
Run Code Online (Sandbox Code Playgroud)

我明白了

old.sh: 2: old.sh: Syntax error: "(" unexpected
Run Code Online (Sandbox Code Playgroud)

如果我去掉括号,我会得到

old.sh: 2: old.sh: declare: not found
old.sh: 5: old.sh: Bad substitution
Run Code Online (Sandbox Code Playgroud)

sud*_*dus 5

如果您在脚本的开头添加 crunchbang 行以强制 shell 解释器使用该bash语法,而不是默认使用旧sh语法,则它会起作用。(它在没有 crunchbang 线的情况下也适用于我,但出于多种原因,使用 crunchbang 线是个好主意。)

我创建了该文件arraytest

#!/bin/bash

declare -a arr=("element1" "element2" "element3")

for i in "${arr[@]}"
do
   echo "$i"
done
Run Code Online (Sandbox Code Playgroud)

然后我使它可执行并执行它。

chmod ugo+x arraytest

$ ./arraytest
element1
element2
element3
Run Code Online (Sandbox Code Playgroud)