[英]Unbound variable not causing exit from subshell when set -eu
$ 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
现在,如果 wc 失败,您将不会看到不should not get here
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.