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

Jas*_*son 7 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
Run Code Online (Sandbox Code Playgroud)

我正在运行bash版本4.1.2.有没有办法确保子shell中所有这些未绑定变量的使用导致脚本退出而不必修改涉及子shell的每个调用?

小智 7

更好的解决方案,以确保可变的卫生处理

#!/usr/bin/env bash

set -eu

if [[ ${1-} ]]; then
  DNE=$1
else
  echo "ERROR: Please enter a valid filename" 1>&2
  exit 1
fi
Run Code Online (Sandbox Code Playgroud)

通过在花括号内的变量名称中加一个连字符,这样可以让bash灵活地处理未定义的变量.我也强烈建议您查看Google shell样式指南,这是一个很好的参考https://google.github.io/styleguide/shell.xml

[[ -z ${variable-} ]] \
  && echo "ERROR: Unset variable \${variable}" \
  && exit 1 \
  || echo "INFO: Using variable (${variable})"
Run Code Online (Sandbox Code Playgroud)


P.P*_*.P. 3

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

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

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