What is the difference between `./example.sh` and

2019-03-04 17:02发布

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?

标签: linux bash shell
3条回答
趁早两清
2楼-- · 2019-03-04 17:17

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 a bash, where such syntax is allowed for arrays.

When you launch it via sh example.sh then sh 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 than bash (Bourne again shell). You don't have such arrays. Note that in sh the first line of your script is just interpreted as a comment.

查看更多
3楼-- · 2019-03-04 17:20
array_name=(value1 ... valuen)

This is how to initializes an array in bash only. When you execute ./example.sh, the shebang line #!/bin/bash tells the system to use bash to execute.

However, when you execute sh example.sh, sh is used to execute. In many Unix systems (like Linux), sh is equivalent to bash. It seems sh is a different shell on your system.

查看更多
看我几分像从前
4楼-- · 2019-03-04 17:22

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.

查看更多
登录 后发表回答