变量未设置的bash脚本 [英] bash script with variables not getting set

查看:52
本文介绍了变量未设置的bash脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看似简单的bash脚本来设置我的环境: 前两行是:

I have a seemingly simple bash script to setup my environment: The first two lines are:

#!/bin/bash
export CVE_ENV_DIR=$PWD

容易,嘿?好吧,看看运行它会发生什么,我得到以下输出:

easy, hey? Well, see what happens when I run it, I get the following output:

$ echo $PWD
/work/env
$ ./env.sh 
$ echo $CVE_ENV_DIR

$ 

为什么未将CVE_ENV_DIR设置为/work/env?这是怎么回事当我在外壳上手动输入export CVE_ENV_DIR=$PWD时,它会按预期工作...

Why does CVE_ENV_DIR not get set to /work/env? What is happening here? When I type export CVE_ENV_DIR=$PWD manually on the shell, it works as expected...

推荐答案

子级shell不会影响其父级的环境.如果您希望脚本影响父母的环境,则需要:

Child shells cannot affect the environment of their parent. If you want the script to affect the parent's environment, you need to:

source ./env.sh

那是怎么回事?当您通过bash env.shenv.sh运行bash脚本时,您将生成一个具有其自身环境的程序,该环境与其父级环境分离.但是,当您在命令行上运行脚本中包含的命令或使用source时,则没有生成环境.

So what's going on? When you run a bash script, either by bash env.sh or env.sh, you're spawning a program with its own environment, an environment that's divorced from its parent. But, when you run the commands contained in the script at the command line, or using source, there is no spawned environment.

编辑以解决@syme的评论.打算使用source读取的Bash脚本通常是纯配置,仅包含分配和计算.还可以通过聪明的她爆炸来使它们更具帮助性并进行自我记录,例如:

Edit to address @syme's comment. Bash scripts meant to be read using source are often pure configuration, containing only assignments and calculations. It's possible to also make them a little more helpful and self-documenting with a clever she-bang hack like:

#!/bin/echo USAGE: source 
# Default configuration file for the Frobnicator package.

FOO=bar
BAR=$(stat /baz)
[[ -f /baz ]] && BAZ=file || BAZ=

export FOO BAR BAZ

使用于配置的bash脚本像配置脚本一样 look ,可以帮助将来的维护人员.您还可以帮助我自己将脚本代码模块化为不同的部分,每一部分都有其独特的功能.

Making a bash script meant for configuration look like a configuration script, you help future maintainers. You also help yourself my modularizing your script code into distinct parts, each part with its one unique function.

请注意,请勿导出与您分配的同一行.

这篇关于变量未设置的bash脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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