Sample Header Ad - 728x90

How does the system decide which shell runs a script without a shebang line?

1 vote
0 answers
151 views
I have this "script" on my Arch Linux system:
$ cat ~/scripts/foo.sh
ps -hp $$
It will simply run ps on its own PID. But the script has no shebang line. I was expecting that in the absence of a specific shebang, the system would run this either using whatever interactive shell I used to launch it, or using whatever I have set as $SHELL. However, I see that it does change depending on which shell I am running but it isn't consistent: 1. If I launch it from a bash session, it is run by bash:
$ ps -hp $$ 
    1267979 pts/15   Ss     0:00 /bin/bash
    $ foo.sh
    1276346 pts/15   00:00:00 bash
2. If I launch it from a zsh session, it is run by sh (which is bash on my system):
% ps -hp $$ 
    1279855 pts/15   S      0:00 zsh
    % foo.sh
    1280006 pts/15   S+     0:00 sh /home/terdon/scripts/foo.sh
3. If I launch it from an sh session, it is run by sh again:
$ ps -hp $$
    1281052 pts/15   S      0:00 sh
    $ foo.sh
    1281296 pts/15   S+     0:00 sh
4. If I launch it from an tcsh session, it is run by sh again:
> ps -hp $$
    1281968 pts/15   S      0:00 -csh
    > foo.sh
    1282148 pts/15   S+     0:00 /bin/sh /home/terdon/scripts/foo.sh
5. If I launch it from a dash session, it is run by sh yet again
$ ps -hp $$
    1282803 pts/15   S      0:00 dash
    $ foo.sh
    1283404 pts/15   S+     0:00 /bin/sh /home/terdon/scripts/foo.sh
So it looks like bash is the only shell that will run a script using itself when the script is launched from a bash session and all the others I tested will use sh instead. This isn't related to whether /bin/sh is bash or another shell. I also tested on an Ubuntu system whose /bin/sh is dash and got the same behavior: bash would run the script using itself, dash and zsh would run it using sh. On both my Arch and the Ubuntu system mentioned above, my SHELL variable is set to /bin/bash and my user's entry in /etc/passwd has /bin/bash as my default shell. Questions: * Who controls this? Is it the kernel or the shell? Is this a bash feature (i.e. bash will use itself in the absence of a shebang)? Something else? * Why do the shells behave differently? Why do I have so many different formats in the output of ps? I see sh /home/terdon/scripts/foo.sh and sh alone, and /bin/sh /home/terdon/scripts/foo.sh. What's going on here? I realize these are all equivalent, but it's surprising to see so many different ways of launching the same essential job.
Asked by terdon (251605 rep)
Mar 17, 2023, 12:47 PM
Last activity: Mar 17, 2023, 01:24 PM