user3437721
user3437721

Reputation: 2299

Replacing environment variables in bashrc

I can retrieve a list of environment variables from a remote system, which prints out the environment variable like this:

some command | awk -F ": " '/SOME_VAR/ {print "export "$1"="$2}'

will give

export SOME_VAR_ABC=999
export SOME_VAR_XYZ=123
export SOME_VAR_TUV=654
etc

Is there a way I can then loop through and write these directly to my bashrc, but overwrite the variable if it already exists?

Upvotes: 1

Views: 1731

Answers (1)

mtnezm
mtnezm

Reputation: 1027

Maybe a cleaner way to avoid duplicates of the variables you retrieve from the remote machine (which makes me think their value may change over time) is to write them down to a separate file apart from your .bashrc and then load that file into your .bashrc file.

For example, let's call it ~/.custom_variables. To get the variables retrieved from the remote machine into this file, you can run the following command:

some command | awk -F ": " '/SOME_VAR/ {print "export "$1"="$2}' > ~/.custom_variables

And then you would only have to add this to your .bashrc:

if [ -f ~/.custom_variables ]; then
  source ~/.custom_variables
fi

This way every time you run that command the file ~/.custom_variables will be overwritten, and thus you would not have to worry about duplicate entries.

Upvotes: 5

Related Questions