简体   繁体   中英

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM