首页 > 解决方案 > bash - 将变量从脚本加载到主 shell

问题描述

您将如何将声明到脚本中的变量加载到主 shell 中?

例如,我有一个从网页获取凭据的脚本(示例),我希望这些凭据可用于运行该脚本的主 shell。

到目前为止,我尝试导出变量,例如:

export uvar="user"
export pvar="password"

这在脚本之外不起作用。

然后我尝试将这些变量发送到一个文件中,然后获取该文件,然后删除该文件,如下所示:

echo 'uvar="user"' >> /tmp/testfile1
echo 'pvar="password"' >> /tmp/testfile1
. /tmp/testfile1
rm /tmp/testfile1

运行上述脚本后,不会为主 shell 加载变量。

然后我尝试做同样的事情,但在我的文件中使用预制函数.bashrc,如下所示:.bashrc 文件:

loadfunc() {
    echo "loading variables from /tmp/testfile1"
    . /tmp/testfile1
}
export -f loadfunc

现在这确实有效,loadfunc可以在脚本中调用该函数,export -f loadfunc因为echo会出现,如下所示:

echo 'uvar="user"' >> /tmp/testfile1
echo 'pvar="password"' >> /tmp/testfile1
loadfunc
rm /tmp/testfile1

但问题是,在获取文件后,这些变量对主 shell 不可用。

有谁知道如何做到这一点?不过,这必须在一个脚本中完成。

标签: bash

解决方案


许多必须更改您的环境的实用程序,例如nvm更改节点版本和venv我认为的pythons包装器,所以是这样的:

安装文件.sh

function load_the_vars {
  uvar=user
  pvar=$1 # set this from an argument
}

这个函数可以做各种动态的东西,甚至可以接受命令行参数

接着

$ source vars.sh # source the file to load the function
$ load_the_vars new-password
$ # and then the vars are set
$ echo $uvar $pvar
user new-password

您可以vars.sh在 .bashrc 中获取源代码,以便始终安装它,然后您可以随时调用它定义的函数。

获取文件并定义函数后,您可以查看如下定义:

$ type load_the_vars
load_the_vars is a function
load_the_vars () 
{ 
    uvar=user;
    pvar=$1
}

否则,您可以在 bash 文件中内联执行此操作,并在需要时获取该文件:

动作文件.sh

uvar=user
pvar=password
$ source action-file.sh
$ echo $uvar $pvar
user password

如果您需要将导出的变量传递到您运行的另一个程序中,则将它们导出到您的源文件或您定义的函数中


推荐阅读