3
#!python3
print("Hello")

I find that this code works fine in my terminal. But everyone does #!/path/to/file or #!/usr/bin/env command.

Is there any reason to avoid using #!command in shebang lines?

4
  • How do you run the script? What shell do you use?
    – choroba
    Jan 10 at 13:22
  • FWIW, it's common enough to write a shebang like #!python at the top of Python scripts on Windows, because they are sufficient for interpretation by the py utility. Jan 11 at 5:30
  • I used zsh in my macos terminal.
    – egrr
    Jan 11 at 19:25

1 Answer 1

12

A path-less shebang assumes that the command in the shebang is in the current directory, in the general case. More generically, a non-absolute shebang is interpreted relative to the current directory of the process executing the script.

Path-less shebangs where the command isn’t in the current directory work only when the script is started from certain shells (Zsh at least, but not Bash), and it works because the shell helps out. When the script is run, execution fails, but the rule then is for the shell to try to run the script if it thinks it is a script; Zsh looks up shebang commands in its path, but that’s not standard.

Scripts with path-less shebang commands won’t work in any other context.

The idiomatic way to write a PATH-based shebang is to use /usr/bin/env, as you mention:

#! /usr/bin/env python3

or, with some versions of env,

#! /usr/bin/env -S python3 --

to avoid problems with paths to the script starting with dashes.

3
  • Might be worth mentioning that it will also work if called explicitly using python, which might be what the OP is doing: python3 script.py.
    – terdon
    Jan 10 at 13:34
  • It doesn't use PATH? Jan 10 at 14:29
  • 1
    @DanielWalker Zsh does, but that’s not standard. Jan 10 at 14:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .