$ cat test.sh
set -eu
echo "`wc -l < $DNE`"
echo should not get here
$ /bin/bash test.sh
test.sh: line 2: DNE: unbound variable
should not get here
我正在运行bash版本4.1.2。有没有办法确保所有这样在子shell中使用未绑定变量的用法都会导致脚本退出,而无需修改涉及子shell的每个调用?
$ cat test.sh
set -eu
echo "`wc -l < $DNE`"
echo should not get here
$ /bin/bash test.sh
test.sh: line 2: DNE: unbound variable
should not get here
我正在运行bash版本4.1.2。有没有办法确保所有这样在子shell中使用未绑定变量的用法都会导致脚本退出,而无需修改涉及子shell的每个调用?
确保变量清洗的更好解决方案
#!/usr/bin/env bash
set -eu
if [[ ${1-} ]]; then
DNE=$1
else
echo "ERROR: Please enter a valid filename" 1>&2
exit 1
fi
在花括号内插入连字符,就像这样的变量名称,可以使bash合理地处理未定义的变量。我还强烈建议查看Google shell风格指南,它是一个很好的参考https://google.github.io/styleguide/shell.xml
[[ -z ${variable-} ]] \
&& echo "ERROR: Unset variable \${variable}" \
&& exit 1 \
|| echo "INFO: Using variable (${variable})"
使用一个临时变量,以便让test.sh进程了解wc
的失败情况。您可以将其更改为:
#!/bin/bash
set -eu
out=$(wc -l < $DNE)
echo $out
echo should not get here
-e
实际上是用于调试目的。它不提供任何有用的信息;它只是失败了。除此之外,检查错误的通常方法是使用变量 $?
来捕获返回代码。 - P.Pset -o nounset
。 - P.P