1

Doing some tests, I discovered that setting the bash shebang in a script would cancel the $BASH_SUBSHELL behavior.

# in the terminal $ echo $BASH_SUBSHELL 0 $ (echo $BASH_SUBSHELL) 1 

script_no_shebang.sh

echo $BASH_SUBSHELL 
$ ./script_no_shebang.sh 0 $ test=$(./script_no_shebang.sh) $ echo $test 1 

script_shebang.sh

#!/bin/bash echo $BASH_SUBSHELL 
$ ./script_shebang.sh 0 $ test=$(./script_shebang.sh) $ echo $test 0 

Any idea if this is a bug or an expected behavior ?

I tried several combinations as tested above. Using a lot of bash functions I don't see myself removing the shebang to use $BASH_SUBSHELL.

1 Answer 1

1

When the script starts with a shebang, the operating system kernel executes the shebang as a command, with the script name as its argument. So it's equivalent to running

/bin/bash ./script_shebang.sh 

This starts a new bash process that initializes the subshell level to 0.

When there's no shebang, the shell executes the script itself in a subshell, so it increments the subshell level.

You can see the equivalent of the shebang if you do

test=$(/bin/bash ./script_no_shebang.sh) 

Basically, starting a new bash instance is not the same as a subshell.

Sign up to request clarification or add additional context in comments.

10 Comments

Thank you, I will validate your answer. Any idea how to bypass this behavior, so I could detect if I am executing my script in a subshell or not ?
Use an environment variable that you increment yourself, not a variable that's counting something different from what you want.
Note that not all shells do this. bash and ksh do. zsh and dash will fork sh to execute the script instead. fish just reports an error.
Moral of the story: if your script is expected to be executed by bash, make sure it has a shebang or you explicitly execute the script with bash.
If this is anything more than curiosity over an unexpected difference, I suspect they aren't using BASH_SUBSHELL correctly.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.