设置-eu时,bash未绑定变量不会导致从子shell退出

时间:2013-02-09 19:51:07

标签: bash 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的每个调用?

2 个答案:

答案 0 :(得分:5)

确保可变消毒的更好解决方案

#!/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})"

答案 1 :(得分:2)

使用临时变量,以便让test.sh进程了解wc的失败。您可以将其更改为:

#!/bin/bash
set -eu
out=$(wc -l < $DNE)
echo $out
echo should not get here

现在,如果wc失败,你将看不到should not get here

相关问题