Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a new environment variable in UNIX....?

How to create a new environment variable in unix and use it in a program??????

like image 385
user205688 Avatar asked Jun 14 '10 06:06

user205688


People also ask

Which command can create environment variable in Unix?

You can create a variable on the command line by using a command like “myvar=11”, but it's not really an environment variable unless you also export it and it won't be available in subshells. If, instead, you typed “export myvar=11”, the variable will then also be available if you initiate a subshell.

How do you create a new variable in the environment?

On the Windows taskbar, right-click the Windows icon and select System. In the Settings window, under Related Settings, click Advanced system settings. On the Advanced tab, click Environment Variables. Click New to create a new environment variable.


3 Answers

You can tell what shell you're running by ps -o comm= -p $$ — I think that's more-or-less universal. So, in bash and certain similar shells...

If you want to create the variable for one specific run, you can do

MYVAR=value the_command_that_needs_myvar

If you want to create it for an entire shell session (ie. until you log out):

export MYVAR=value

...and then you can run:

the_command_that_needs_myvar

...as many times as you like during that session, and it will still see MYVAR as having the value value.

If you want it to be set for yourself, for all your login sessions, put it in ~/.profile.

Please note that bash's initialisation files can be one great big WTF. Depending on whether it is run interactively, over a network, locally, AND depending on whether it is invoked as sh or bash, it will selectively read some combination of ~/.bashrc, ~/.profile and ~/.bash_profile. Read the FILES section of the bash man page for details.

If you want it to be set for every user, every time they log in, put it in the file /etc/profile (although there's also /etc/environment, I'm not sure how widely used that is.).

Check out the question "How to set environment variable for everyone under my linux system?" for some more details, too.

(Beware, some of this advice will vary depending on if you, or other users, use bash, dash, csh, ksh, etc... but it should work for most use cases.)

like image 125
detly Avatar answered Oct 04 '22 19:10

detly


Depends on the shell. In bash, you can use:

export myvar=xyz

which will set the variable and make it available to other programs.

If you want to set it for one invocation of a program, you can use:

myvar=xyz ./myprog

This will have it set for the myprog process but not after it exits.

like image 40
paxdiablo Avatar answered Oct 04 '22 18:10

paxdiablo


See setenv(3) and getenv(3) functions.

like image 31
Daniel Băluţă Avatar answered Oct 04 '22 19:10

Daniel Băluţă