[Linux] #!/bin/sh and #!/bin/bash, what is the difference, combined with code examples and common exception handling

#!/bin/sh and #!/bin/bash, what is the difference, combined with code examples and common exception handling

#!/bin/shBoth and #!/bin/bashare the beginning of the script file, which are used to specify the interpreter of the script file. where #!/bin/shspecifies the Bourne shell interpreter and #!/bin/bashspecifies the Bash shell interpreter.

The Bash shell is an enhanced version of the Bourne shell that supports more features and syntax. Therefore, if you need to use Bash shell-specific syntax or features in your script, you need to use #!/bin/bashto specify the interpreter.

Here is a simple example that demonstrates the difference between the two interpreters:

#!/bin/sh

echo "Hello, world!"

# 使用 Bash 特有的语法
if [[ 1 -eq 1 ]]; then
  echo "1 equals 1"
fi

In the above example, [[ ... ]]the syntax is used, which is specific to the Bash shell. If you use #!/bin/shto specify the interpreter, an error will be reported:

./test.sh: 6: [[: not found

Therefore, the correct approach is to use #!/bin/bashto specify the interpreter.

Common exception handling includes:

  1. Interpreter does not exist: If the specified interpreter does not exist, an error will be reported. This can be avoided by checking for the existence of the interpreter.
  2. Insufficient permissions: If the script file does not have execution permissions, an error will be reported. You can add execution permission to the script file through chmod +xthe command.
  3. Syntax error: If there is a syntax error in the script file, an error will be reported. You can check for syntax errors by executing the script file at the command line.

Guess you like

Origin blog.csdn.net/qq_41604569/article/details/131292435