1

I want to set a environment variable globally for all users in linux.

In order to do that I modified /etc/environment file.

For example at the end of file.

sudo sh -c 'echo "\nmyenv=hello" >> /etc/environment'

After executing this command when in run in the same terminal.

echo $myenv

i'm not getting the value hello.

After typing the below command.

source /etc/environment 

I'm able to access the environment variable in command prompt with

echo $myenv

But the problem in this method is if i execute a sh file. Which is accessing the $myenv. I need to again type the command
source /etc/environment in that shell script.

Please let me know what is going wrong here.

Please suggest me what is the approach followed here.

I don't what to logoff and logon or restart my server.

1
  • 1
    /etc/environment is parsed by pam_env. Commented Jan 21, 2018 at 19:23

1 Answer 1

2

An environment variable is only inherited by child processes if it is exported.

myenv=hello
export myenv
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the reply , So where i need to type this command. Because sudo sh -c 'echo "\nmyenv=hello" >> /etc/environment' is done by one script and it is accessed by another script.
Actually don't put this precise syntax in /etc/environment because it is shared with other shells. Instead, add export myenv on a separate line.
@tripleee Can yo please provide me with some examples. Please find the explanation. I have a script which is creating an environment variable. This environment variable is added to /etc/environment. Because i want this for different users. Now from this script if i'm invoking a child process i need to write export myenv=hello after adding it to environment file. But in my case i'm manually execute the same script again in the same terminal. So I want to check the environment variable there on the second execution of batch script.
John's answer is basically correct and explains how to achieve this. My comment pertains to tweaking the syntax so it doesn't only work with Bash; this file will need to usable by other Bourne-compatible shells like Dash etc too. Once you have the export there you can source this file from your current shell (or even from the soript which just added it, though that will obviously only affect the script's own environment).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.