How to export a variable in bash

被刻印的时光 ゝ 提交于 2019-11-28 12:07:13
Jeremy Cantrell

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.

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)"

EDIT: Corrected the second option to be eval rather than source. Opps.

Set the variable in /etc/profile (create the file if needed). That will essentially make the variable available to every bash process.

Set the variable in /etc/profile (create the file if needed). That will essentially make the variable available to every bash process.

...to every NEW bash process...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!