4

When we print the console settings with the echo $- command, we output himBHs by default. However, when we run the same command in any script file, we only output hB.

root@root:~# echo $-
himBHs
root@root:~# ./abc.sh 
hB
root@root:~#

What I'm wondering is, even though we're running the script from a /bin/bash environment, why don't the same default settings apply ?

For example, when I start a new sub-shell process with the command /bin/bash on the console and list the settings, I get output himBHs.

root@root:~# /bin/bash
root@root:~# echo $-
himBHs

When I try to perform the same process from within the shell file, the output I get is "hB".

root@root:~# ./abc.sh 
hB

I've tried the same process with shebang and without the shebang, but my script file is either bash script_file or ./script_file if I run, it gives the same result(hB).

What exactly am I missing?

muru
  • 72,889
testter
  • 1,410

2 Answers2

5

Because when you run a script, the parent shell (the one you run your commands from) starts a non-interactive shell to run your script which has interactive flag disabled i and only turns on two options

  • -h to locate and remember (hash) commands as they are looked up for execution.
  • -B to allow the shell to perform brace expansion

You can see the complete list of set options which will be seen in the output of $- - The Set Builtin

Other options available in the interactive shell, -i to indicate to run the shell in interactive mode

  • -m to allow Job control
  • -H to enable ! style history substitution
Inian
  • 12,807
4

Several settings are enabled (or disabled) by default depending on whether the Bash is being run interactively, in POSIX mode, or other things. For example, from the output of help set:

  -H  Enable ! style history substitution.  This flag is on
      by default when the shell is interactive.

Or:

  -p  Turned on whenever the real and effective user ids do not match.

It just happens that for an interactive, non-POSIX-mode Bash, the options enabled are himBHs (-i is for interactive mode, -s is for reading in commands from standard input, the other options are listed in help set).

muru
  • 72,889
  • 2
    QuickQ: Why doesn't the GNU bash manual explain about the -s flag explicitly? or am I missing something here? – Inian Jan 28 '20 at 08:06
  • @Inian it's mentioned in Invoking Bash. If you're asking why it being listed in $- isn't explained, that's probably an oversight. It's only necessary to use it explicitiy for interactive shells if you have a non-option argument. – muru Jan 28 '20 at 08:48
  • 1
    You are wrong for -p. It needs to be set from outside to prevent the shell from resetting the effective uid/gid. – schily Jan 28 '20 at 11:52