简体   繁体   English

bash将如何处理未设置的变量

[英]what will bash do with an unset variable

I am confused by the behavior about how do bash treat a unset variable used in a shell command, like below: 我对bash如何处理shell命令中使用的未设置变量的行为感到困惑,如下所示:

rm -rf /$TO_BE_REMOVED

what will be done if i have not defined a variable TO_BE_REMOVED . 如果我还没有定义变量TO_BE_REMOVEDTO_BE_REMOVED

If you do that, the command executed will effectively try to remove / which is very, very bad. 如果这样做,执行的命令将有效地尝试删除/ ,这是非常非常糟糕的。 I mean, it will probably mostly fail (unless you're running as root), but still, it will be very bad. 我的意思是,它可能大多会失败(除非您以root身份运行),但仍然会很糟糕。

You can avoid many of these sorts of bugs in Bash automatically with one simple command: 您可以使用一个简单的命令自动避免Bash中的许多此类错误:

set -eu

If you put that at the top of your Bash script, the interpreter will stop and return an error code if your script ever invokes a command which returns an error which is not checked (that's the -e part), or if it uses an undefined variable (the -u part). 如果将其放在Bash脚本的顶部,则解释器将停止并返回错误代码,如果您的脚本曾经调用了一个返回未检查错误的命令(即-e部分),或者使用了未定义的错误变量( -u部分)。 This makes Bash considerably safer. 这使得Bash更加安全。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM