Introduction
In bash scripting, we often see the sequence of characters #! appear at the beginning of the line. This sequence of characters is called shebang.
shebang is used to proclaim the interpreter that the operating system must use to compile the syntax of the command in the file.
Here is the guide on how to use bash shebang in Linux as we go through below.
The syntax of shebang
#!interpreter [arguments]
interpreter maybe /bin/sh, /bin/bash.
[arguments] is optional.
How to use shebang in bash scripts
If the shebang is not specified with any arguments, the script will be compiled by the default random interpreter used by that shell. In order for your script to be properly interpreted with bash, you need to add the path for the shebang to execute the script.
Have two ways to use shebang as an interpreter. The first way is to proclaim the file path to the executable:
#!/bin/bash
The 2nd way: using the env utility:
#!/usr/bin/env bash
The advantage of the second way is, it will look for the executable in the $PATH environment variable.
With debug mode:
With bash: you need to add -x after the shebang line:
#!/bin/bash -x
With the env utility, you need to add set -x:
#!/usr/bin/env bash
set -x
Example of shebang
Firstly, let’s create a file named “hello” by your text editor:
$ nano hello
Then type the following command:
Save the file.
Before running the script, let’s add execute permission to file by the chmod command:
$ chmod +x hello
Now you can try running the script by typing ./
$ ./hello
Output:
Overriding the shebang bash
If you want to override the interpreter while the shebang bash defined the interpreter to use, let’s follow the syntax:
$ <interpreter> <script>
For example, the hello file above is being interpreted with bash. Now I want it follows the sh interpreter:
$ sh hello
Output:
*Note: You shouldn’t override the shebang bash because it will adversely affect the progress of the script.
Conclusion
You’ve already gone through the details of how to use bash shebang in Linux.
Thanks for reading.