Bash脚本:如果未设置环境变量,则设置环境变量

huangapple go评论84阅读模式
英文:

Bash script to set an environment variable if unset

问题

我编写了一个bash脚本来设置环境变量`VAR`,如果它当前尚未设置:

example.sh
```bash
#!/bin/bash

if [ -z $VAR ]; then
    export VAR=abc
fi

现在我在命令行中输入:./example.sh && echo $VAR。我期望得到abc,但结果是空白的。为什么?


<details>
<summary>英文:</summary>

I wrote a bash script to set the environment variable `VAR` if it is currently not set:

example.sh
```bash
#!/bin/bash

if [ -z $VAR ]; then
    export VAR=abc
fi

Now I type this in the command line: ./example.sh &amp;&amp; echo $VAR. I expect abc, but the result is blank. Why?

答案1

得分: 1

Use source example.sh or . example.sh

英文:

Use source example.sh or . example.sh

huangapple
  • 本文由 发表于 2023年2月6日 16:58:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75359177.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定