Trung Quan Vo
Trung Quan Vo

Reputation: 429

Set environment variables for non-interactive shell

I'm trying to set environment variables for non-interactive non-login shell. I know bash reads the contents of ~/.bashrc before execute the command. In the beginning of the script there's a part:

*# If not running interactively, don't do anything

case $- in
*i*) ;;
  *) return;;
esac*

So I think if I add something above it, it will take effect no matter if the shell is interactive or not:

export VAR=something

# If not running interactively, don't do anything

case $- in
*i*) ;;
  *) return;;
esac

However it doesn't work :(. I want to avoid using $BASH_ENV because it messes up my xkb settings. I remapped some keys in /usr/share/X11/xkb/symbols/pc. And if I set $BASH_ENV, it will just loads the default keymap.

Upvotes: 13

Views: 26010

Answers (2)

tripleee
tripleee

Reputation: 189387

The details are somewhat platform-dependent. Bash Startup Files in the reference manual describes the default behavior of Bash itself; but you also need to take into account the behavior of your particular platform.

In general, $HOME/.bashrc is executed for non-interactive login shells, but no script can be guaranteed to run for a non-interactive non-login shell. You can force it by setting (and exporting!) BASH_ENV from a parent shell to the name of a script which you want to execute when a non-interactive shell is started.

Sometimes, an acceptable workaround is to run a script in a login shell, and trust that the non-interactive non-login script you run inherits whatever parameters you set in the login shell. This is what e.g. /etc/environment can do; but it does not force a piece of script to run at the time when a noninteractive shell is subsequently started (except of course if you use /etc/environment to set up BASH_ENV as described above).

Upvotes: 2

Trung Quan Vo
Trung Quan Vo

Reputation: 429

Solution for Ubuntu: set the variables in /etc/environment, and it works for all users and all types of shells.

Upvotes: 17

Related Questions