Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 4 down vote accepted

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.

share|improve this answer
    
Thanks for the broad answer, I know I didn't provide enough context. This is to set up an EC2 instance that hosts a Node.js app. –  Nico Sep 20 '13 at 16:33

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.