在脚本中好的做法解封定义的全局变量? [英] Is unsetting global variables defined in a script good practice?

查看:72
本文介绍了在脚本中好的做法解封定义的全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它是好的做法,写sh脚本时,来取消所有previously在脚本的末尾定义的全局变量?

Is it considered good practice, when writing sh scripts, to unset all previously defined global variables at the end of the script?

如果举例来说,我执行我的剧本的MyScript 使用。 (源)内置,像这样

If for example, I execute my script myscript using the . (source) builtin, like this

. myscript

执行脚本后壳poluted在脚本中定义的变量。这似乎是非常糟糕的(特别是如果被其他人使用)。

after executing the script the shell is poluted with the variables defined in the script. This seems really bad (especially if used by other people).

如果我可以,我就会在SH(或bash)摆脱全局干脆但更多的时候则不是,他们是最最坏的解决方案: - )

If I could, I would get rid of globals in sh (or bash) altogether but more often then not they are the least worst solution :-).

推荐答案

这是不是真的执行脚本。这是采购的,这使得外壳程序执行脚本中的每个命令。如果要执行该脚本,你可以这样做:

This isn't really executing the script. It is sourcing it, which makes the shell execute each command inside the script. If you want to execute the script, you would do this:

./myscript

和在这种情况下,没有被设置在脚本内的环境变量的会对你的壳的效果。

And in that case, none of the environment variables that are set inside the script would have an effect on your shell.

如果你真的需要源脚本,以便它可以做的事情一样设置环境变量或者改变当前目录,那么你可以使用括号隔离子shell里的变量:

If you really need to source the script, so that it can do things like set environment variables or change your current directory, then you can isolate the variables inside a sub-shell using parentheses:

(
  a=7
  echo $a
)
# The change in a doesn't get to here

如果您要取消设置你使用的变量,你将有相反的问题。如果具有相同名称的变量已经由用户设置,那么你最终会摧毁它。

If you were to unset the variables you use, you would have the opposite problem. If a variable with the same name had been set by the user, then you would end up destroying it.

这篇关于在脚本中好的做法解封定义的全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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