Friday, July 29, 2022

[SOLVED] How to export a variable in Bash

Issue

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?


Solution

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.



Answered By - Jeremy Cantrell
Answer Checked By - Katrina (WPSolving Volunteer)