我的shell脚本中为什么数组是错误的?

4
我一直在寻找这个问题的答案。我在我的shell脚本中有一个数组,但运行时出现错误:"(" unexpected。请问我做错了什么?我使用的是Ubuntu 11.10。
您需要将代码更改为以下格式才能在Shell中使用: array=(1 2 3 4 5) 在数组元素之间不需要添加空格。
4个回答

10

您正在使用/bin/sh运行脚本,而不是/bin/bash。在sh中没有数组。

choroba@cyan ~$ /bin/sh
$ a=( 1 2 3 )
/bin/sh: Syntax error: "(" unexpected

0

尝试在运行脚本时指定单词bash,如下所示:

$ bash script.sh

0
你在使用bash吗?
$ bash --version
GNU bash, version 3.2.48(1)-release (x86_64-apple-darwin11)
Copyright (C) 2007 Free Software Foundation, Inc.
$ array=( 1 2 3 4 5 )
$ echo ${array[1]}
2
$ 

是的,这个没问题。然而,脚本出了些问题没有运行。 - Michael S.
奇怪...当我将整个脚本复制粘贴到终端时,它可以运行。为什么作为外部文件就不起作用呢? - Michael S.
@user1068559,你可以尝试使用 sh --verbose -x script.sh 命令来运行脚本,并查看它在哪里出错。http://tldp.org/LDP/abs/html/arrays.html 这个网站也可能对你有所帮助。 - jackdoe
嗯...不幸的是没有透露太多信息。我知道脚本是有效的,所以问题肯定出在其他地方的某些小细节上。 - Michael S.

0

有时候也是因为空格太多的缘故:

array = (1 2 3 4)

不正确。应该是:

array=(1 2 3 4)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接