bash - 在不指定值的情况下声明变量

时间:2017-03-09 21:35:16

标签: bash

我正在试图弄清楚如何在不为其赋值的情况下声明变量。根据bash doc,这应该没问题:

  

声明[-aAfFgilnrtux] [-p] [name [= value] ...]

     

声明变量和/或赋予它们属性。

“= value”位是可选的,但是使用“declare var”而没有赋值似乎没有做任何事情。

#!/bin/bash

function check_toto_set() {
  if [ -z "${toto+x}" ] ; then
    echo toto not defined!
  else
    echo toto=$toto
    echo toto defined, unsetting
    unset toto
  fi
}

function set_toto() {
  declare -g toto
}

function set_toto_with_value() {
  declare -g toto=somevalue
}

check_toto_set
toto=something
check_toto_set
declare toto
check_toto_set
set_toto
check_toto_set
set_toto_with_value
check_toto_set

基本上我希望“没有定义!”只是为了第一个“check_toto_set”,所有其他人都应该找到toto被声明,即使是空的但是输出是:

toto not defined!
toto=something
toto defined, unsetting
toto not defined!
toto not defined!
toto=somevalue
toto defined, unsetting

我在ubuntu上使用bash 4.3.46

echo $BASH_VERSION
4.3.46(1)-release

所以我误解了声明的内容,或者我是否测试变量是否设置错误? (我正在使用来自How to check if a variable is set in Bash?的信息)

1 个答案:

答案 0 :(得分:3)

您正在测试变量是否设置(甚至是空值)。这与它是否被宣布不同。

要确定是否已声明,您可以使用declare -p

varstat() {
  if declare -p "$1" >/dev/null 2>&1; then
    if [[ ${!1+x} ]]; then
      echo "set"
    else
      echo "declared but unset"
    fi
  else
    echo "undeclared"
  fi
}

export -f varstat

bash -c 'varstat toto'                 # output: "undeclared"
bash -c 'declare toto; varstat toto'   # output: "declared but unset"
bash -c 'declare toto=; varstat toto'  # output: "set"