未找到Bash中的数组

Waf*_*fle 7 linux bash

我试图在bash中声明一个数组,但是当代码运行时它说它找不到数组.我试图用几种不同的方式写出数组的声明,但似乎无论我如何声明它我都无法让它工作.我原本试图这样声明:

candidate[1]= 0
candidate[2]= 0
candidate[3]= 0
Run Code Online (Sandbox Code Playgroud)

返回的错误消息是:

votecalculation.sh: 13: candidate[1]=: not found
votecalculation.sh: 14: candidate[2]=: not found
votecalculation.sh: 15: candidate[3]=: not found
Run Code Online (Sandbox Code Playgroud)

在此之后我尝试了另一种在线发现的解决方案

ARRAY=( 'can1' 'can2' 'can3' )
Run Code Online (Sandbox Code Playgroud)

使用它时会返回此错误:

votecalculation.sh: 12: Syntax error: "(" unexpected
Run Code Online (Sandbox Code Playgroud)

我是Bash的新手,我对阵列感到很困惑.我需要一些特定的方式来声明一个数组,还是我只是完全错了?

Chr*_*Lee 7

它可能不喜欢等号后面的空格.

其他一些想法:

  • 确保你实际上使用bash来运行你的脚本,而不是sh/dash.

  • 您可以使用显式声明变量为数组 declare -a varname


Bry*_*yan 5

 #!/bin/bash

 myarray[0]=hello
 myarray[1]=world

 echo ${myarray[0]}
 echo ${myarray[1]}
Run Code Online (Sandbox Code Playgroud)

保存到helloworld.bash

执行使用../helloword.bash