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 at Ibmi Media, as part of our Server Management Services, we regularly help our Customers to perform related Linux system bash queries.
In this context, we shall look into how to use bash shebang in Linux.
The syntax of shebang is shown below:
#!interpreter [arguments]interpreter maybe /bin/sh, /bin/bash.
In this command, [arguments] is optional.
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.
There are two ways to use shebang as an interpreter. The first way is to proclaim the file path to the executable:
#!/bin/bashThe second way is by using the env utility:
#!/usr/bin/env bashThe 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 -xWith the env utility, you need to add set -x:
#!/usr/bin/env bashset -x
Firstly, let's create a file named "hello" by your text editor:
$ nano helloThen type the following command:
#!/bin/bash
echo "Hello World"Save the file.
Before running the script, let’s add execute permission to file by the chmod command:
$ chmod +x helloNow you can try running the script by typing ./
$ ./helloThe Output will be:
Hello WorldIf 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 we want it follows the sh interpreter:
$ sh helloOutput will be:
Hello World*Note: You shouldn't override the shebang bash because it will adversely affect the progress of the script.
This article covers how to use bash shebang in Linux. In fact, the first line in the scripts starts with the #! characters and the path to the Bash interpreter is called shebang and is used to tell the operating system which interpreter to use to parse the rest of the file.
The #! syntax used in scripts to indicate an interpreter for execution under UNIX / Linux operating systems. Most Linux shell and perl / python script starts with the following line:
#!/bin/bash
OR
#!/usr/bin/perlOR
#!/usr/bin/pythonOR
#!/usr/bin/python3OR
#!/usr/bin/env bashsh is the standard command interpreter for the system. The current version of sh is in the process of being changed to conform with the POSIX 1003.2 and 1003.2a specifications for the shell.