Bash 数组:意外的语法错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11026192/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 02:29:27  来源:igfitidea点击:

Bash array: Unexpected Syntax error

arraysbashshellsyntax

提问by user1357576

I am writing this simple bash script as follows.

我正在编写这个简单的 bash 脚本,如下所示。

#!/bin/bash

array=( /home/abc/Downloads/something.bat /home/abc/Downloads/smb.conf )
echo ${array[@]}

I expected it to print all the names of the files in the array. But I get this error instead:

我希望它打印数组中文件的所有名称。但我收到了这个错误:

test.sh: 3: Syntax error: "(" unexpected

If I change the declaration of array to

如果我将数组的声明更改为

array = {/home/abc/Downloads/something.bat /home/abc/Downloads/smb.conf}

this error goes away but I still have new errors

这个错误消失了,但我仍然有新的错误

test.sh: 3: array: not found
test.sh: 4: Bad substitution

How can I resolve this issue? This is my first time in shell programming so I am unable to fix the issues myself.

我该如何解决这个问题?这是我第一次使用 shell 编程,所以我无法自己解决这些问题。

RESOLVED:

解决:

I was executing it as sh test.sh but I forgot I had to execute it as bash test.sh

我将它作为 sh test.sh 执行,但我忘了我必须将它作为bash test.sh执行

回答by Marc B

Variable assignments can't have a space around the =sign:

变量赋值不能在=符号周围有空格:

array=( /a/b/  /c/d )
     ^--no spaces 


are you sure?

你确定吗?

marc@panic:~$ array =(a b)      
bash: syntax error near unexpected token `('
marc@panic:~$ array= (a b)  
bash: syntax error near unexpected token `('
marc@panic:~$ array = (a b)
bash: syntax error near unexpected token `('
marc@panic:~$ array=(a b)  
marc@panic:~$ echo ${array[1]}
b

回答by Chad WALSTROM

Pointer: Spaces are important with variable assignment in BASH. Don't use them beforeor afterthe equal sign.

指针:空格对于 BASH 中的变量赋值很重要。不要在等号之前之后使用它们。

回答by shellter

Are you using a DOS editor to create your script?

您是否使用 DOS 编辑器来创建脚本?

Bash etc shells, don't like CRLF pairs, just LF (or \r\nchars VS just plain \nchar).

Bash 等 shell,不喜欢 CRLF 对,只喜欢 LF(或\r\n字符 VS 只是普通\n字符)。

Put your script thru this test

把你的脚本通过这个测试

cat -vet myScript.sh

Do you see '^M' chars at the end of lines? If so that is a dos file.

你在行尾看到 '^M' 字符吗?如果是这样,那就是一个dos文件。

See if your system has dos2unix then use it like

看看你的系统是否有 dos2unix 然后像这样使用它

dos2unix myScript.sh

Also, as several people have commented on it, please edit your original question to eliminate the spaces around your =signs in the assignments to array.

此外,由于有几个人对此发表了评论,请编辑您的原始问题,以消除=分配给array.

I hope this helps.

我希望这有帮助。