1

Must the shebang header always match the interpreter's installation directory? If so, then why do both #!/usr/bin/python and #!/usr/local/bin/python work for me?

3 Answers3

7

As others have noted, the shebang line must refer to an actual file that exists.

Since different systems can have binaries installed to different locations, this is a weakness of script portability.

One way to solve this is with links, as others have mentioned.

Another way is to edit the script to refer to the right path on your system.

One more way to get around this is to use /usr/bin/env, which will find the executable in your PATH.

So instead of:

#!/usr/bin/python

Write:

#!/usr/bin/env python

This way, people just have to symlink /usr/bin/env if needed, rather than every individual executable.

Of course, the executable still has to be in your PATH for this to work...

As you can see, there is no 100% clean solution. Remember: "Worse is Better" (:

jwd
  • 1,467
5

The #! (shebang) line must specify an executable that actually exists. If both work on your system, it means you have a python installed in both places. Or, possibly, a symlink.

Normally, you'd get an error attempted to use an interpreter that doesn't exist:

anthony@Zia:~$ /tmp/test 
bash: /tmp/test: /usr/local/bin/python: bad interpreter: No such file or directory

If you instead run the script like this, then the path likely doesn't matter:

anthony@Zia:~$ python /tmp/test
anthony@Zia:~$ 

That's because you're running python directly, and passing it an argument. Python then decides to open that file and treat it as a script. In the first case, the kernel is attempting to run the script as an executable. It checks it, notices shebang line, and attempts to convert it to the second form, so it can actually run it. That fails if the path given after #! doesn't actually exist.

derobert
  • 109,670
3

Shebang is a combination of the following characters: #! when it appears in the first line of the script. The following string is always the path to the interpreter. I'd check what exactly /usr/bin/python and /usr/local/bin/python are. It's possible that one of them is a symlink into the other. Could you please, provide the output of the following commands:

  • ls -l /usr/bin/python
  • ls -l /usr/local/bin/python
jasonwryan
  • 73,126
  • avimehenwal@AviMehenwal-DYNAC:~/Documents/PYTHON$ python p1.py Hello World avimehenwal@AviMehenwal-DYNAC:~/Documents/PYTHON$ python p2.py Hello World avimehenwal@AviMehenwal-DYNAC:~/Documents/PYTHON$ ls -l /usr/bin/python lrwxrwxrwx 1 root root 9 Feb 24 23:27 /usr/bin/python -> python2.7 avimehenwal@AviMehenwal-DYNAC:~/Documents/PYTHON$ ls -l /usr/local/bin/python ls: cannot access /usr/local/bin/python: No such file or directory – avimehenwal Feb 27 '13 at 21:32