如何让 bash 将未定义的变量视为错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41020844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 15:30:24  来源:igfitidea点击:

How can I make bash treat undefined variables as errors?

linuxbashshell

提问by Robert Kubrick

Please note: there are many questions about how to test a single shell variable on this site. This question is about testing a script for any undefined variable.

请注意:关于如何在此站点上测试单个 shell 变量有很多问题。这个问题是关于测试任何未定义变量的脚本。

You can use an undefined variable in bash without seeing any error at execution:

您可以在 bash 中使用未定义的变量而不会在执行时看到任何错误:

#!/bin/bash

echo ${UNDEF_FILE}
ls -l ${UNDEF_FILE}

exit 0

I've found this very error prone. If I want to change the name of a variable in a large script, or remove that variable, all the previous stale references will cause errors in the script. Sometimes this is not obvious to debug or you find out when it's too late.

我发现这很容易出错。如果我想在一个大脚本中更改一个变量的名称,或者删除该变量,所有以前的陈旧引用都会导致脚本中出现错误。有时这对调试来说并不明显,或者您发现为时已晚。

Why is this allowed? Is there any way to flag undefined variables?

为什么这是允许的?有没有办法标记未定义的变量?

回答by anubhava

You can use:

您可以使用:

set -u

at the start of your script to throw an error when using undefined variables.

在脚本的开头使用未定义的变量时抛出错误。

-u

Treat unset variables and parameters other than the special parameters "@" and "*" as an error when performing parameter expansion. If expansion is attempted on an unset variable or parameter, the shell prints an error message, and, if not interactive, exits with a non-zero status.

-u

执行参数扩展时,将未设置的变量和特殊参数“@”和“*”以外的参数视为错误。如果在未设置的变量或参数上尝试扩展,shell 会打印一条错误消息,如果不是交互式的,则以非零状态退出。

回答by kojiro

set -uis the more general option, but as pointed out in other answers' comments, there are problems writing idiomatic shell scripts with set -uin play. An alternative is to create parameter expansions that yield an error when a specific variable isn't set.

set -u是更通用的选项,但正如其他答案的评论中指出的那样,编写惯用的 shell 脚本存在问题set -u。另一种方法是创建参数扩展,当未设置特定变量时会产生错误。

$ echo $foo

$ echo $?
0
$ echo "${foo?:no foo for yoo}"
bash: foo: :no foo for yoo
$ echo $?
1

This error will cause a non-interactive shell to exit. This gives you a quick way to guarantee an error condition won't allow control flow to continue with an undefined value. The specdoes not require an interactive shell to exit, although it's worth noting that even in an interactive shell, bash will return from a function call if this error occurs in a function.

此错误将导致非交互式 shell 退出。这为您提供了一种快速的方法来保证错误条件不会允许控制流继续使用未定义的值。该规范不要求退出交互式 shell,但值得注意的是,即使在交互式 shell 中,如果函数中发生此错误,bash 也会从函数调用中返回。