How to export a system environment variable in bash

I need to set a system environment variable from a bash script that will be available outside the current scope. Thus, you usually export environment variables as follows:

export MY_VAR = / opt / my_var

But I need an environment variable available at the system level. Is it possible?

+7
linux bash sysadmin
source share
4 answers

This is the only way I know what you want:

In foo.sh you have:

#!/bin/bash echo MYVAR=abc123 

And when you want to get the value of a variable, you should do the following:

 $ eval "$(foo.sh)" # assuming foo.sh is in your $PATH $ echo $MYVAR #==> abc123 

Depending on what you want to do and how you want to do it, you can use the Douglas Leader’s suggestion to use the source, but it will be the source of the whole file, functions and everything. Using eval, only material that receives an echo will be evaluated.

+5
source share

Not really - once you work in a subprocess, you cannot influence your parent.

There are two possibilities:

1) Correct the script, and do not run it (see source. ):

     source {script}

2) Output the script commands for the export commands, and eval:

     eval `bash {script}`
 OR:
     eval "$ (bash script.sh)"

EDIT: Fixed the second option, which should be eval, not the source. Opps.

+13
source share

Set the variable in the / etc / profile file (create a file if necessary). This will make the variable available for each bash process.

+1
source share

Set the variable in the / etc / profile file (create a file if necessary). This will make the variable available for each bash process.

... to each process NEW bash ...

0
source share

All Articles