-1

How can I have bash respect the shebang when passing a file as an argument?

eg: hello.py

#!/usr/bin/env python
print("Hello Python")

When passed to bash:

$ bash hello.py
hello.py: line 2: syntax error near unexpected token `"Hello Python"'
hello.py: line 2: `print("Hello Python")'

In the environment I’m using I unfortunately can’t execute hello.py directly, it has to be done by supplying args to bash.

tekumara
  • 8,357
  • 10
  • 57
  • 69
  • 1
    Of course Bash ignores it, it's a comment; shebangs are meant for the kernel. You want to run `/usr/bin/env python hello.py`, right? Just want to make sure cause I could also imagine having Bash error with a more descriptive error message is another option. – wjandrea Dec 23 '21 at 05:06
  • 2
    `bash SOMEFILE` executes _SOMEFILE_ as a bash script. This is described in the bash man page. You could write `bash -c ./hello.py` to force the #! line being considered (provided that _hello.py_ is executable), but this would create one additional (unnecessary) child process, as you could run it equally well simply by `./hello.py`. – user1934428 Dec 23 '21 at 08:08

1 Answers1

4

Don't run scripts with an explicit interpreter. Always execute them by just typing the script name; that way the interpreter listed in the shebang will be used.

$ ./hello.py

This will require that the script is executable so make sure to do that if you haven't already.

$ chmod +x hello.py

If you have to run bash then use -c to pass a full command and stop it from trying to read it as a bash script:

$ bash -c './hello.py'
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • If I had interactive access I would, but in the environment I’m using I can only pass args to bash. I was hoping to find some combination that would trigger bash to select the shebang interpreter but perhaps this isn’t possible? – tekumara Dec 24 '21 at 12:31