7
$ 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的每个调用?

4

2 回答 2

12

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

#!/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})"
于 2016-02-26T01:03:53.300 回答
2

使用临时变量,让 test.sh 进程知道wc. 您可以将其更改为:

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

现在,您不会看到should not get hereif wc 失败。

于 2013-02-09T19:55:13.567 回答