简体   繁体   中英

export /etc/environment variables to current environment; from a shell script?

How do I bring environment variables from /etc/environment to the terminal and what it calls?

file0.bash

#!/usr/bin/env bash

bash ./file1.bash
echo $FOO_BAR

for line in $( sudo cat /etc/environment ); do export $line; done

file1.bash

#!/usr/bin/env bash

sudo sed -i '/^FOO_BAR/d' /etc/environment
printf FOO_BAR="$HOME/Foo\n" | sudo tee -a /etc/environment

for line in $( sudo cat /etc/environment ); do export $line; done

Console

$ echo $FOO_BAR

$ bash file0.bash
[sudo] password for myusername: 
FOO_BAR=/home/myusername/Foo

$ echo $FOO_BAR

$ # What I want to avoid is having to revert to this:
$ for line in $( sudo cat /etc/environment ); do export $line; done
$ echo $FOO_BAR
/home/myusername/Foo

When you execute a script as:

bash ./file.bash

OR else:

./file1.bash

Running a shell script like this launches a new process, a subshell .

All the variables created in a subshell are not visible outside the block of code in the subshell. They are not accessible to the parent process, to the shell that launched the subshell. These are, in effect, variables local to the child process. Note that exporting variables also won't make them available in the parent shell. That just makes them available to further subshells of the running subshell.

To change this behavior you can force script to execute in current shell itself using any of these 2 way:

source ./file1.bash

OR

. ./file1.bash

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM