Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export a variable in Bash

I need to set a system environment variable from a Bash script that would be available outside of the current scope. So you would normally export environment variables like this:

export MY_VAR=/opt/my_var

But I need the environment variable to be available at a system level though. Is this possible?

like image 670
mbrevoort Avatar asked Nov 20 '08 22:11

mbrevoort


People also ask

What does it mean to export a variable in Bash?

It means that the shell's child processes do not inherit the shell's variables. The user must export the variables to make them available to child processes. This tutorial will show you how to export Bash variables in Linux using the export command. Access to the terminal/command line. The bash shell.


2 Answers

Not really - once you're running in a subprocess you can't affect your parent.

There two possibilities:

  1. Source the script rather than run it (see source .):

    source {script}
    
  2. Have the script output the export commands, and eval that:

    eval `bash {script}`
    

    Or:

    eval "$(bash script.sh)"
    
like image 173
Douglas Leeder Avatar answered Sep 26 '22 03:09

Douglas Leeder


This is the only way I know to do what you want:

In foo.sh, you have:

#!/bin/bash
echo MYVAR=abc123

And when you want to get the value of the variable, you have to 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, Douglas Leeder's suggestion about using source could be used, but it will source the whole file, functions and all. Using eval, only the stuff that gets echoed will be evaluated.

like image 28
Jeremy Cantrell Avatar answered Sep 24 '22 03:09

Jeremy Cantrell