Bash – Linux Redhat 7 : How to set a shell option globally / system-wide

bashlinuxrhelshellshopt

I'm having some troubled time trying to figure out how to turn on the xpg_echo option of the bash for every shell that will get run on my Linux RedHat system (7.4).

I know I can have what I need (the purpose is to expands backslash-escape at anytime as all the shells are ported from an HP-UX server) by using shopt -s xpg_echo, it's working fine for most cases.

Now my problem is where to turn on this option "system-wide" or "globally" so that every shell that I will run uses it.

I tried putting shopt -s xpg_echo into one custom shell in /etc/profile.d/myshell.sh.

It's working fine for:

  • Interactive shell sessions (get's sourced from /etc/bashrc)
  • Login shell sessions (get's sourced from /etc/profile)
  • shell programs without a bash shebang (that is no #!/bin/bash on 1st row)

but I can't get it to work in following cases, as it seems the /etc/profile.d/ scripts don't get sourced and the xpg_echo option is not inherited from the calling shell:

  • when running a shell script (with for example echo "a\tb") as a bash argument, e.g. bash /tmp/mytest.sh
  • when running a shell script that has the bash shebang (#!/bin/bash) on 1st row

I'd like to know if there is any way to turn on the shell option xpg_echo for every conditions where I need to run a shell.

NB: I'm using GNU bash, version 4.2.46

Best Answer

Thanks for pointing me to another related topic.

To me the key was using the BASH_ENV variable.

As noted in the bash reference manual, there are several way to open a shell, the one causing me trouble was when it was invoked "non-interactively".

To workaround the fact that non-interactive shell don't run any /etc/profile nor /etc/bashrc, I created a dedicated shell script in /etc/profile.d/, e.g. "custom_shopts.sh" with only the shopt options that I'd like to have for every session and in this same script I will export variable BASH_ENV=/etc/profile.d/custom_shopts.sh

Therefore, in any shell that I run (login shell, interactive shell or non-interactive shell, but with the exception of bash --posix), the /etc/profile.d/custom_shopt.sh shell script will get run and position the shopt options I'm expecting.

Related Question