0

I've come across a behavior I can't explain. When I run a bash script without a shebang, the ps command will not show the script and its arguments as arguments passed to bash, neither will /proc/$$/cmdline, whereas If I run the script with a shebang, behavior is as expected.

Example with a shebang:

# cat mytest
#!/bin/bash
echo my name is $1
cat /proc/$$/cmdline
echo
ps -p $$ -o args=

# ./mytest John
my name is John
/bin/bash./mytestJohn
/bin/bash ./mytest John

Example without a shebang:

# cat mytest
echo my name is $1
cat /proc/$$/cmdline
echo
ps -p $$ -o args=

# ./mytest John
my name is John
-bash
-bash

In both cases the script will display 'my name is John', but without a shebang I see the bash process without any arguments. How is this possible?

boogie
  • 349
  • 1
  • 3
  • 11
  • Without a shebang, the script is run with `/bin/sh`, which makes the output of `-bash` puzzling beyond the lack of arguments. – chepner Nov 23 '15 at 13:15
  • 1
    @chepner - without a shebang it does not and should not run with /bin/sh - not with bash. The default behavior for bash is to create another bash subprocess when the shebang isn't specified but this is not the problem anyway. I just wonder how the bash subprocess runs without the script name (and it's name argument) as its argument – boogie Nov 23 '15 at 13:44
  • `bash` itself doesn't look at the shebang. If a file is marked as executable, it simply passes the name of the file to one of the system calls in the `exec` family, and the OS itself uses the shebang to determine what program to use to interpret the script. Lacking a shebang, it attempts to use the system shell, which on a POSIX-compliant system is `/bin/sh`. – chepner Nov 23 '15 at 15:15
  • 1
    @chepner - Please read my comment. I **did not** say that bash reads the shebang(that's done by execve). In fact, to quote myself, I said **"without a shebang.....when the shebang isn't specified"**. Also, from the bash man page: "If this execution fails because the file is not in executable format, and the file is not a directory, it is assumed to be a shell script, a file containing shell commands. **A subshell** is spawned to execute it." - thus bash and not sh is spawned. – boogie Nov 24 '15 at 11:23

0 Answers0