问:
假设我有这个脚本:
export.bash
#! /usr/bin/env bash
export VAR="HELLO, VAR"
当我执行脚本并尝试访问 $VAR 时,我没有得到任何值!
echo $VAR
有没有一种方法可以通过只执行 export.bash 而不 source 它获取 $VAR?
答:
不可以。
但是有几种可能的解决办法。
最明显的方法,你已经提到过,是使用 source 或 . 在调用 shell 的上下文中执行脚本:
$ cat set-vars1.sh
export FOO=BAR
$ . set-vars1.sh
$ echo $FOO
BAR
另一种方法是在脚本中打印设置环境变量的命令,而不是设置环境变量:
$ cat set-vars2.sh
#!/bin/bash
echo export FOO=BAR
$ eval "$(./set-vars2.sh)"
$ echo "$FOO"
BAR
在终端上执行 help export 可以查看 Bash 内置命令 export 的帮助文档:
# help export
export: export [-fn] [name[=value] ...] or export -p
Set export attribute for shell variables.
Marks each NAME for automatic export to the environment of subsequently
executed commands. If VALUE is supplied, assign VALUE before exporting.
Options:
-f refer to shell functions
-n remove the export property from each NAME
-p display a list of all exported variables and functions
An argument of `--' disables further option processing.
Exit Status:
Returns success unless an invalid option is given or NAME is invalid.
参考:
相关阅读:
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有