How to create a new environment variable in unix and use it in a program??????
See setenv(3) and getenv(3) functions.
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.)
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.