top of page
Search
understandingdevop

What is shebang? Why #!/usr/bin/python or /usr/bin/env python on the very first line of the script?

When we start writing any scripts, now let's take an example of python.

Now I have started writing my python script in which I have defined all our classes functions etc. etc. When you save that file and come back on the terminal to execute the script, how do you execute it?

root@rootshellcoffee# ./myscript.py 

If you execute in this fashion and if you haven't defined a shebang inside your script, on the very first line, your operating system won't understand where is the binary file for executing this script? How does your script know that? where is your python executable with which it should execute your python script?

For that, we define #!/usr/bin/python or /usr/bin/env python on the first line, so when the script starts the execution it compiles the script from top to bottom and finds the defined interpreter and figures out that this scripts binary is present in /usr/bin/python.


Let's see a demonstration of the execution of the python script with a shebang and without shebang so that we will get a clear understanding.

First scenario without shebang:- I have printed a simple statement in my python script without defining shebang.

root@rootshellcoffee#cat event.py
print ("This is python script") 
=================================================================
root@rootshellcoffee#./event.py 
./event.py: line 1: syntax error near unexpected token `"This is python script"'
./event.py: line 1: `print ("This is python script")'
=================================================================root@rootshellcoffee#python event.py
print ("This is python script")

As above you can observe I had to specify python and then script name to execute this python script.


Second scenario with shebang:- I have defined shebang and executed

root@rootshellcoffee#cat event.py 
#!/usr/bin/env python
print ("This is python script")
==================================
root@rootshellcoffee#./event.py 
This is python script

As in the second scenario, you observed that I don't have to give python and then script name, because I have already defined shebang inside the script. So by specifying ./ operating system will automatically figure out it's a binary file specified inside the script and execute the script along with that binary file.



18 views0 comments

Comments


Post: Blog2_Post
bottom of page