I have seen many files which have this line as the first line in them. What exactly is this?
#!/usr/bin/env python
What does it mean? Why is it necessary?
I have seen many files which have this line as the first line in them. What exactly is this?
#!/usr/bin/env python
What does it mean? Why is it necessary?
It's not just
/usr/bin/env python
but#!/usr/bin/env python
and this line is called a shebang.I'm quoting Wikipedia:
In my case (13.10 Desktop),
/usr/bin/env python
will default to python2.7 but it could be python3.4 depending on your system defaults (e.g. 14.04 Server).A line like this can appear on the first line of interpreted programs or scripts. It is a directive to the program loader to pass the file to the interpreter - in this case Python.
Interpreter directives are placed on the first line of an executable script after the characters
#!
(called a shebang or hashbang) so that a script can be executed by just the script name, in one of the following ways from the command line:To be able to execute the script in this way like a command, it must have execute permission.
instead of the interpreter with the script name as an argument which would be required if the interpreter directive was not there, like thus:
#!
is called shebang. Normally, Bash considers the symbol#
as a comment, however upon seeing#!
Bash knows that the rest of the content should be a script and the first line will refer to which program or interpreter to invoke. In the case of#!/usr/bin/env python
Bash knows that this line is invoking the correct "environment settings" for the Python interpreter. Thus the rest of the file's content will be run using the Python interpreter. Had the line been like#!/bin/bash
or#!/usr/bin/perl
Bash would have run the content using Bash (itself) or Perl respectively.You can still write a Python, Bash or Perl script without mentioning this line. In that case to run your Python script you'd need to invoke from command line this way:
This is because without shebang
#!
and without a correct interpreter path, Bash would not know it's a script and would treat it as a text file.