Dre
Dre

Reputation: 85

Environment variable change in shell but won't export

I am having issues with setting permanent environment variables in my shell. For example

HISTSIZE=0
export HISTSIZE
echo $HISTSIZE

The variable will change in the shell. But if I open another tab or close and reopen the shell the variable reverts to its original value of 1000.

I have also tried sourcing the variable with a script written in ~/.bash_profile. But it leaves the same issue of the variable only working in that specific shell. How can I create a permanent change?

Upvotes: 3

Views: 3062

Answers (3)

user1934428
user1934428

Reputation: 22225

Look at the bash man page: .bash_profile is only read for interactive login shells. If it is an interactive non-login shell, .bashrc is processed instead.

I suggest putting those settings which should be performed in every interactive shell, into a separate file (say: ~/.bash_interactive) and source this file from .bash_profile and .bashrc.

Upvotes: 0

chepner
chepner

Reputation: 530823

If you open a new tab, the parent process of the new shell isn't your current shell, but your terminal emulator, so exporting HISTSIZE doesn't affect the environment of the new shell.

Since HISTSIZE is only used by the shell itself, there's no need to export it at all. Set its value in .bashrc so that any new interactive shell gets the value initialized.

HISTSIZE=0

If your terminal emulator is configured to start a login shell (common on macOS, I assume much less so in Linux), .bashrc won't be used. In such a case, I recommended adding . .bashrc to the very end of your .bash_profile, so that an interactive login shell is initialized the same as an interactive non-login shell.

Upvotes: 4

Zsolt Botykai
Zsolt Botykai

Reputation: 51583

Some terminal emulator doesn't run new tabs as login shell. E.g. in Gnome Terminal You should:

  1. List item
  2. Go to Edit -> Profile Preferences.
  3. Select the Title and Command tab. Notice how the Run command as login shell checkbox is unchecked! Check it.

Furthermore setting a variable in a shell session does not make it permanent for later sessions. E.g. exporting a variable makes it available for any further processes that's got created from the actual session.

To make it somewhat permanent You have to add it to e.g. .bashrc

Do note:

Shell config files such as ~/.bashrc, ~/.bash_profile, and ~/.bash_login are often suggested for setting environment variables. While this may work on Bash shells for programs started from the shell, variables set in those files are not available by default to programs started from the graphical environment in a desktop session.

Quoted from the Ubuntu help.

So to decide where to add it please read the fine manual

Upvotes: 2

Related Questions