I am trying to play with bash and arrays. But executing a sample script, I got an unexpected syntax error message: example.sh: 3: example.sh: Syntax error: "(" unexpected
. And this is the script
#!/bin/bash
array=( one two three )
If I run the script with ./example.sh it works and no errors are displayed. But if I run sh example.sh
I get the error message.
I thought that these two commands are the same:
- sh example.sh
- ./example.sh
so ... what is the difference between the two?
When you launch it via
./example.sh
then the command specified in the first line of the script is used to interpret the content. So your script executes in abash
, where such syntax is allowed for arrays.When you launch it via
sh example.sh
thensh
is the command that is used to interpret the content of the file.sh
is the original Unix shell (aka Bourne shell) and this shell is a little more rude thanbash
(Bourne again shell). You don't have such arrays. Note that insh
the first line of your script is just interpreted as a comment.This is how to initializes an array in
bash
only. When you execute./example.sh
, the shebang line#!/bin/bash
tells the system to usebash
to execute.However, when you execute
sh example.sh
,sh
is used to execute. In many Unix systems (like Linux),sh
is equivalent tobash
. It seemssh
is a different shell on your system.by using sh example.sh - you are specifying what shell interpreter to use for that script. Example being "bash example.sh" instead of "sh example.sh" etc etc.
Running scripts this way disregards the "shebang (#!/bin/bash)" that you have specified inside of the script. Since you wrote a bash script but are trying to run it as just "sh", this is why it is failing
by using ./example.sh, - You are specifying to run the script from your current directory. This will attempt to run the script in whatever shell you are currently in unless a shebang is specified. Since you have a "shebang" specified to run the script in bash... this is why it is working.