From: H. Thiele To: bug-bash@gnu.org Subject: Odd Behavior: $SHLVL decreases in some situations with a pipe
Configuration Information [Automatically generated, do not change]: Machine: x86_64 OS: darwin14.5.0 Compiler: gcc Compilation CFLAGS: -DSSH_SOURCE_BASHRC uname output: Darwin ***REDACTED***.local 14.5.0 Darwin Kernel Version 14.5.0: Sun Jun 4 21:40:08 PDT 2017; root:xnu-2782.70.3~1/RELEASE_X86_64 x86_64 Machine Type: x86_64-apple-darwin14.5.0 Bash Version: 5.1 Patch Level: 16 Release Status: release Description: In some situations (see Repeat-By) the value of the $SHLVL (Shell Level) variable may unexpectedly decrease by 1, e.g. when the stdout output of "printenv" is redirected to via a pipe. While I noticed the behavior first when I installed the latest bash on my rusty Mac OS X I also was able to reproduce it with bash 5.x under Debian and Raspian on the PI. On the other hand I don't see the effect with the old bash 3.x that came with Mac OS X. Repeat-By: $ printenv SHLVL 1 $ printf "%u\n" $SHLVL 1 $ printenv SHLVL | cat 0 $ printf "%u\n" $SHLVL | cat 1 Note how the result is "0" instead "1" for the 3rd command. Some more experienced users on Reddit (see: https://www.reddit.com/r/bash/comments/vlrkk1/odd_behavior_of_shlvl_environment_variable/) suggest following steps which may provide further clarification for the problem with the hint that it may has something to do with bash's "exec optimization", here is a workaround variant (courtesy of Reddit user aioeu) that successfully forwards the correct information to the next command by inserting a call to "true": $ printenv SHLVL | cat 0 $ { printenv SHLVL; true; } | cat 1 Reddit user Electronic_Youth points out some other, perhaps related issue: if one sets SHLVL to a value higher than 999 a warning is generated when a new shell is started, but more interesting a warning is generated two times when printenv is used (perhaps suggesting some code runs twice?) I reproduced that double warning like this: $ SHLVL=1001 $ printenv SHLVL | cat bash: warning: shell level (1000) too high, resetting to 1 bash: warning: shell level (1000) too high, resetting to 1 1