How to create a new environment variable in UNIX…?

前端 未结 3 1941
深忆病人
深忆病人 2021-02-06 04:40

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

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-06 05:17

    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.)

提交回复
热议问题