Bash – Are all the shell options not inherited by scripts

bash

If I run set -x and then run a script in a shell, the option set by set -x doesn't work inside the script.

I was wondering if all the shell options are not inherited by scripts?

I didn't find this is mentioned in bash manual. The only relevant that I found is "Unless otherwise noted, the values are inherited from the shell." So I guess shell options are inherited. Do I miss it in the manual?

I have read a related question which asked how to let scripts inherit shell options. I was wondering whether and why instead of how.

Thanks.

When a simple command other than a builtin or shell function is to be
executed, it is invoked in a separate execution environment that
consists of the following. Unless otherwise noted, the values are
inherited from the shell.

• the shell’s open files, plus any modifications and additions
specified by redirections to the command

• the current working directory

• the fi le creation mode mask

• shell variables and functions marked for export, along with
variables exported for the command, passed in the environment (see
Section 3.7.4 [Environment], page 37)

• traps caught by the shell are reset to the values inherited from the
shell’s parent, and traps ignored by the shell are ignored A command
invoked in this separate environment cannot aff ect the shell’s
execution environment.

Best Answer

In the case of bash, that depends on whether $SHELLOPTS is in the environment or not.

bash-4.4$ export SHELLOPTS
bash-4.4$ set -x
bash-4.4$ bash -c 'echo x'
+ bash -c 'echo x'
+ echo x
x

See how the bash -c 'echo x' inherited the xtrace option. For the options set by shopt, it's the same but with the $BASHOPTS variable.

It comes handy especially for the xtrace option for debugging when you want to run a bash script (or any command running a bash script) and all other bash script it may invoke, recursively with xtrace (provided nothing does a set +x in those scripts). If your sh is bash, that will also affect them, so also the system("command line") made in other languages:

env SHELLOPTS=xtrace some-command
Related Question