MoRe
MoRe

Reputation: 1538

Shebang ignored?

I don't know how to better title the behaviour I just experienced. I arrived from this answer because I'm trying to read the contents of a file into a string.

I have the following script which I made executable:

root@host:~# pwd
/root
root@host:~# ls -l script.sh 
-rwxr-xr-x 1 root root 83 Mar  7 21:25 script.sh
root@host:~# cat script.sh 
#!/usr/bin/env bash
set -e
echo $SHELL
echo "foo" > /root/BAR
echo "$(</root/BAR)"

Now, when I execute this using my current bash instance or explicitly pass it to /bin/bash it executes as expected:

root@host:~# echo $SHELL
/bin/bash
root@host:~# ./script.sh 
/bin/bash
foo
root@host:~# /bin/bash script.sh 
/bin/bash
foo
root@host:~#

However, when I start the script with sh I get the following output (the file is not read) although it looks like it's using the intended shell:

root@host:~# sh script.sh
/bin/bash

root@host:~#

From this answer I figured that the environment variable $SHELL may not be reliable and it turns out that's the case. When I run ps -o command -p $$ inside the script it prints

COMMAND
sh script.sh

which let's me think the shebang is ignored?

Could someone explain to me what's going on please?

As for the file reading without cat, I think I will just call the script explicitly as bash script.py which works.

Upvotes: 0

Views: 38

Answers (0)

Related Questions