简体   繁体   English

Bash 4.0.0中$ @未绑定变量的解决方法?

[英]Work-around for $@ unbound variable in Bash 4.0.0?

In specifically Bash version 4.0.0 , is there any way to work around the use of an empty $@ raising an unbound variable error when set -u is enabled? 在特定的Bash版本4.0.0 ,启用set -u时,是否有任何方法可以解决使用空$@引发未绑定变量错误的问题?

Consider the following: 考虑以下:

#!/usr/bin/env bash-4.0.0-1

set -xvu

echo "$BASH_VERSION"
echo "${BASH_VERSINFO[@]}"

main () {
  printf '%q\n' "${@:-}"
}

main "${@:-}"

Gives me the following output when I provide an empty set of arguments: 当我提供一组空参数时,会提供以下输出:

neech@nicolaw.uk:~ $ ./test.sh

echo "$BASH_VERSION"
+ echo '4.0.0(1)-release'
4.0.0(1)-release
echo "${BASH_VERSINFO[@]}"
+ echo 4 0 0 1 release x86_64-unknown-linux-gnu
4 0 0 1 release x86_64-unknown-linux-gnu

main () {
  printf '%q\n' "${@:-}"
}

main "${@:-}"
./test.sh: line 12: $@: unbound variable

I only see this behaviour in Bash version 4.0.0 . 我仅在Bash 4.0.0版中看到此行为。

I was hoping that using variable substitution ${@:-} would allow me to work around this, but it seems not. 我希望使用变量替换${@:-}可以解决此问题,但事实并非如此。

Is there a way to work around this? 有办法解决这个问题吗?

$@ , $* are special variables so should always be defined it's a bug $@$*是特殊变量,因此应始终将其定义为错误

https://unix.stackexchange.com/questions/16560/bash-su-unbound-variable-with-set-u https://unix.stackexchange.com/questions/16560/bash-su-unbound-variable-with-set-u

a workaround, maybe: 解决方法,也许:

set +u
args=("$@")
set -u

main "${args[@]}"

or maybe also 也许也

main "${@:+$@}"

Why not do error handling on your own? 为什么不自行处理错误? This way you can control exactly what happens when an exception is encountered, for instance return a custom exit code and message for that error, rather than be confined to some predefined behavior. 这样,您可以精确地控制遇到异常时发生的情况,例如返回该错误的自定义退出代码和消息,而不必局限于某些预定义的行为。

function log_error                                                          
{                                                                           
    [[ $# -ne 1 ]] && return 1                                              

    typeset msg="$1"                                                        
    typeset timestamp=$(date "+%F %T")                                      

    echo "[${timestamp}] [ERROR] - $msg " >&2                               
}

if [[ -z "$BASH_VERSION" ]]                                                 
then                                                                        
    log_error "BASH VERSION is not set"                                     
    exit 1                                                                  
fi 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM