设置-eu时,bash未绑定变量不会导致从子shell退出
发布时间:2020-12-16 01:19:40 所属栏目:安全 来源:网络整理
导读:$cat test.shset -euecho "`wc -l $DNE`"echo should not get here$/bin/bash test.shtest.sh: line 2: DNE: unbound variableshould not get here 我正在运行bash版本4.1.2.有没有办法确保子shell中所有这些未绑定变量的使用导致脚本退出而不必修改涉及子sh
$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})" (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |