Skip to content
Advertisement

Evaluating command inside bash script leads to increment in $SHLVL

I have the following bash script (myscript.sh):

#!/bin/bash
$(echo $0)

Now: before sourcing myscript.sh, $SHLVL is 2. After sourcing it, is 3. Why? Shouldn’t the command evaluation exit after echo?

Thank you!

Advertisement

Answer

When you source a script in bash, $0 expands to bash (or at least, the name of the shell bash was started as). So $(echo $0) expands first to $(echo bash), which evaluates to bash, which is then identified as the name of the command to run, so a new shell instance is started. You can observe the nesting by running

echo foo; source myscript.sh; echo bar

First you’ll see the string foo printed, then you’ll be at a prompt in the new shell. Type exit to exit it, and you’ll then see bar printed as your original command list finally completes.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement