The shebang begins with the characters #! followed by the path to the program used to execute the script.
Shebang in Python
Python is a scripting language. Hence, it allows us to specify the version and path of the Python interpreter to use via the shebang.
The syntax for adding a shebang in Python is as shown:
The #! characters are used to denote the beginning of a shebang.
The interpreter allows you to specify the path to the interpreter used to run the script.
Finally, the argument allows you to specify the argument that is passed to the executable specified. For our case, this represents the interpreter used to run the script.
If you want a script to be executed with the latest version of the Python interpreter, add the following entry at the beginning of your script:
The above shebang tells the system to run the script with the Python 3 interpreter.
In the example above, we are using the /usr/bin/env command to get the path to the Python interpreter instead of manually typing it.
The env command allows us to show and retrieve environment variables that are in the system.
Hence, running the command:
launches the installed python interpreter.
Another example of a shebang is as shown below:
In this case, the shebang specifies the full path to the target Python interpreter instead of fetching one from the system’s environment variable.
NOTE that to avoid manually including the path to the interpreter as this may lead to errors if the user does not have an interpreter installed at the set location.
For a script running Python 2 code, you can add a shebang as shown:
Another common and practical function of a shebang is to tell the system that a file is executable without actually calling Python on the file.
Let us take a simple example. Suppose we have a file called hello.py,
$ nano hello.py
Add a simple print statement as shown:
Save and close the file.
Without a shebang, we have to call the python program to run the file:
hi, fellow geeks!
However, if we add a shebang
print("hi, fellow geeks!")
We can run the script as:
$ ./hello.py
The good thing about using the env shebang is that it is cross-platform. This means you don’t have to modify the shebang for every system.
Do I really need a Shebang
Although shebangs are useful and can provide an added benefit to your scripts, it is not necessary you use them.
For example, if you want to run a script as a standalone executable, having a shebang can be very beneficial.
However, if you need to share your code with other developers, including a shebang can lead to issues as not all developers share a similar environment.
Hence, before including a shebang in your script, think of how and who is going to run your script.
Closing
In this article, we discussed the concept of a shebang and its role in scripts. We also illustrated how to work with the Python shebang.