If you are learning Bash scripting by reading other people's code, you may have observed that the script's first line begins with the #! characters and the path to the Bash interpreter.
This sequence of characters (#!) is called Shebang and is used to notify the operating system which interpreter to use to parse the remainder of the file.
Shebang Interpreter Directive
The Shebang interpreter directive has the following form:
- The directive must be the first line in the script.
- The directive must start with shebang #!
- White space following the shebang characters is optional.
- Interpreter is the entire path of a binary file (ex: /bin/sh, /bin/bash).
- Interpreter arguments are optional.
- #!/bin/bash - Uses Bash to parse the file.
- #!/usr/bin/env perl - Uses the env command to locate the path to the perl executable.
- #!/usr/bin/python - Executes the file using the python binary.
Using Shebang in Bash Scripts
Suppose a shebang is not given, and the user executing the Bash script is using another Shell. In that case, the script will be interpreted by whatever that Shell uses as the default interpreter. For example, the default interpreter for Bash is Bash and for zsh is sh. To guarantee that your script will always be translated with Bash, you'll need to provide the executable path using Shebang.
There are two methods to utilize the Shebang directive and set the interpreter.
Using the absolute path to the bash binary:
Using the env utility:
The second technique's benefit is that it will look for the bash executable in the user's $PATH environmental variable. If there is more than one pathway to bash, the script will choose the first one.
When utilizing the first option, add an alternative to the Bash shell and send it to the interpreter. For example, to execute the script in debug mode, you would use #!/bin/bash -x. If you use the env approach, you need to use a set to define the option. To activate the debug mode, you would put set -x after the shebang line.
Let's construct a basic script using Shebang to output "Hello, World." Open your text editor and paste the following line:
nano hello world
echo "Hello, World"
To be able to execute the script without providing the interpreter from the command line, you'll need to make the file executable :
chmod +x hello world
Now if you can execute the script by entering ./ followed by the script name:
Overriding the Shebang
If for any reason, you wish to override the interpreter set in the Shebang line, you need to execute the script by explicitly providing the intended Shell. For example, to execute a script that has #!/bin/sh provided in the Shebang line using the bash shell, you would type:
bash hello world
Please note, it is not a good idea to override the shell interpreter as it may lead to unexpected script behavior.
By now, you should have a decent knowledge of what Shebang is and how to utilize it in your Bash scripts.
If you have any questions or suggestions, please post a remark.