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:
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
If I launch it from a zsh session, it is run by
sh
(which isbash
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
If I launch it from an
sh
session, it is run bysh
again:$ ps -hp $$ 1281052 pts/15 S 0:00 sh $ foo.sh 1281296 pts/15 S+ 0:00 sh
If I launch it from an
tcsh
session, it is run bysh
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
If I launch it from a
dash
session, it is run bysh
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 seesh /home/terdon/scripts/foo.sh
andsh
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.
sh script.sh
, others reportingsh
and others reporting/bin/sh script.sh
. Is it just down to how each shell launches its subprocesses? And is any of this user specific (are$SHELL
or the user's passwd entry relevant) or is it always/bin/sh
? – terdon Mar 17 '23 at 13:08ps
variations. – Stephen Kitt Mar 17 '23 at 14:56