Setting user environment variable permanently, outside shell

environment-variables

Is it possible to set up an envinronment variable that can be accessible from any shell, not an specific one, and that doesn't decay as soon as your session ends?

I'd like to set up a NODE_ENV variable system wide, how could I achieve that?

Best Answer

If all the shells you're interested in are Bourne-compatible, you can use /etc/profile for this purpose.

The header of /etc/profile:

# /etc/profile: system-wide .profile file for the Bourne shell (sh(1))
# and Bourne compatible shells (bash(1), ksh(1), ash(1), ...)

To ensure you've got csh and tcsh covered, you can also add your variables to /etc/csh.login.

The header of /etc/csh.login:

# /etc/csh.login: system-wide .login file for csh(1) and tcsh(1)

For zsh, you want /etc/zshenv.

For ease of maintenance

I would write all the variables you want in a single file and write a simple Perl (or other) script that would read these variables and update the relevant files for all the shells.

Something like the following in Perl should work:

 #!/usr/bin/perl

use strict;
use warnings;

my $bourne_file = '/etc/profile';
my $csh_file = '/etc/csh.login';
my $zsh_file = '/etc/zshenv';
open my $BOURNE,'>>', $bourne_file;
open my $CSH,'>>', $csh_file;
open my $ZSH,'>>', $zsh_file;
while(<DATA>){
    chomp;
    my $delimiter = ','; #Change , to whatever delimiter you use in the file

    my ($var, @value) = split /$delimiter/;        
    my $value = join $delimiter,@value;
    print $BOURNE qq{export $var="$value"\n};
    print $CSH    qq{setenv $var "$value"\n};
    print $ZSH    qq{export $var="$value"\n};
}
close $BOURNE;
close $CSH;
close $ZSH;
__DATA__
var1,val1
var2,val2

You can use a delimiter other than , to delimit variables and values as long as this delimiter isn't allowed in variable names.

This can be further tidied up by inserting unique delimiters around the portion you want your script to write in each file so that each time you use the script to update the files, it doesn't duplicate previous entries but substitutes them in situ.

Related Question