shar
shar

Reputation: 2078

Use of shebang in shell scripts

In Linux, we usually add a shebang in a script to invoke the respective interpreter. I tried the following example.

I wrote a shell script without a shebang and with executable permission. I was able to execute it using ./. But if I write a similar python program, without shebang, I am not able to execute it.

Why is this so? As far as my understanding, shebang is required to find the interpreter. So how does shell scripts work, but not a python script?

Upvotes: 3

Views: 909

Answers (5)

Josh Lee
Josh Lee

Reputation: 177574

There’a subtle distinction here. If the target is a binary or begins with a #! shebang line, then the shell calls execv successfully. If the target is a text file without a shebang, then the call to execv will fail, and the shell is free to try launching it under /bin/sh or something else.

Upvotes: 2

Kranthi
Kranthi

Reputation: 83

http://en.wikipedia.org/wiki/Shebang_(Unix)

Under Unix-like operating systems, when a script with a shebang is run as a program, the program loader parses the rest of the script's initial line as an interpreter directive; the specified interpreter program is run instead, passing to it as an argument the path that was initially used when attempting to run the script.

Now when the #! is not found, every line is interpreted as native shell command. And hence if you write a bash script and run it under bash shell it will work. If you run the same bash script in say a tcsh shell it will not work without the initial #!/usr/bin/tcsh

Upvotes: 0

Andres Olarte
Andres Olarte

Reputation: 4380

By default the shell will try to execute the script. The #! notation came later

Upvotes: 3

Joran Beasley
Joran Beasley

Reputation: 113968

shell scripts will only work if you are in the shell you targeted ... there is not python shell ... as such python will never work without explicity calling python (via shebang or command line)

Upvotes: 4

pjmorse
pjmorse

Reputation: 9294

My assumption is that a script without a shebang is executed in the current environment, which at the command line is your default shell, e.g. /bin/bash.

Upvotes: 5

Related Questions