如何使bash将未定义的变量视为错误? [英] How can I make bash treat undefined variables as errors?

查看:235
本文介绍了如何使bash将未定义的变量视为错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

#!/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?

推荐答案

您可以使用:

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.

这篇关于如何使bash将未定义的变量视为错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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