Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
905 views
in Technique[技术] by (71.8m points)

bash - I am getting error "array.sh: 3: array.sh: Syntax error: "(" unexpected"

I have written the following code:

#!/bin/bash
#Simple array
array=(1 2 3 4 5)

echo ${array[*]}

And I am getting error: array.sh: 3: array.sh: Syntax error: "(" unexpected

From what I came to know from Google, that this might be due to the fact that Ubuntu is now not taking "#!/bin/bash" by default... but then again I added the line but the error is still coming.

Also I have tried by executing bash array.sh but no luck! It prints blank.

My Ubuntu version is: Ubuntu 14.04

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Given that script:

#!/bin/bash
#Simple array
array=(1 2 3 4 5)

echo ${array[*]}

and assuming:

  • It's in a file in your current directory named array.sh;
  • You've done chmod +x array.sh;
  • You have a sufficiently new version of bash installed in /bin/bash (you report that you have 4.3.8, which is certainly new enough); and
  • You execute it correctly

then that should work without any problem.

If you execute the script by typing

./array.sh

the system will pay attention to the #!/bin/bash line and execute the script using /bin/bash.

If you execute it by typing something like:

sh ./array.sh

then it will execute it using /bin/sh. On Ubuntu, /bin/sh is typically a symbolic link to /bin/dash, a Bourne-like shell that doesn't support arrays. That will give you exactly the error message that you report.

The shell used to execute a script is not affected by which shell you're currently using or by which shell is configured as your login shell in /etc/passwd or equivalent (unless you use the source or . command).

In your own answer, you say you fixed the problem by using chsh to change your default login shell to /bin/bash. That by itself should not have any effect. (And /bin/bash is the default login shell on Ubuntu anyway; had you changed it to something else previously?)

What must have happened is that you changed the command you use from sh ./array.sh to ./array.sh without realizing it.

Try running sh ./array.sh and see if you get the same error.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...