我可以将变量从 Bash 脚本导出到环境中而不使用它吗? [英] Can I export a variable to the environment from a Bash script without sourcing it?

查看:14
本文介绍了我可以将变量从 Bash 脚本导出到环境中而不使用它吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个脚本:

export.bash:

#! /usr/bin/env bash
export VAR="HELLO, VARIABLE"

当我执行脚本并尝试访问 $VAR 时,我没有得到任何值!

When I execute the script and try to access to the $VAR, I don't get any value!

echo $VAR

有没有办法只执行 export.bash 而无需采购它来访问 $VAR?

Is there a way to access the $VAR by just executing export.bash without sourcing it?

推荐答案

是否有任何方法可以通过仅执行 export.bash 而无需获取它来访问 $VAR ?

Is there any way to access to the $VAR by just executing export.bash without sourcing it ?

快速回答:否.

但是有几种可能的解决方法.

But there are several possible workarounds.

最明显的,你已经提到过,是使用 source. 在调用 shell 的上下文中执行脚本:

The most obvious one, which you've already mentioned, is to use source or . to execute the script in the context of the calling shell:

$ cat set-vars1.sh 
export FOO=BAR
$ . set-vars1.sh 
$ echo $FOO
BAR

另一种方法是让脚本,而不是设置环境变量,打印将设置环境变量的命令:

Another way is to have the script, rather than setting an environment variable, print commands that will set the environment variable:

$ cat set-vars2.sh
#!/bin/bash
echo export FOO=BAR
$ eval "$(./set-vars2.sh)"
$ echo "$FOO"
BAR

第三种方法是使用脚本在内部设置您的环境变量,然后在该环境中调用指定的命令:

A third approach is to have a script that sets your environment variable(s) internally and then invokes a specified command with that environment:

$ cat set-vars3.sh
#!/bin/bash
export FOO=BAR
exec "$@"
$ ./set-vars3.sh printenv | grep FOO
FOO=BAR

最后一种方法可能非常有用,但它不便于交互使用,因为它没有为您提供当前 shell 中的设置(以及您建立的所有其他设置和历史记录).

This last approach can be quite useful, though it's inconvenient for interactive use since it doesn't give you the settings in your current shell (with all the other settings and history you've built up).

这篇关于我可以将变量从 Bash 脚本导出到环境中而不使用它吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆