2017-03-09 80 views
0

我想知道如何聲明一個變量而不向它賦值。據bash的文檔,這應該是確定:bash - 聲明一個變量而不指定值

聲明[-aAfFgilnrtux] [-p] [名稱[=值] ...]

聲明變量和/或給他們的屬性。

「= 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 

基本上我會期望有「toto not defined!」只爲先「check_toto_set」,和所有其它的應該找到TOTO正在申報,即便是空的,但輸出繼電器是:

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

我使用Ubuntu的

echo $BASH_VERSION 
4.3.46(1)-release 

慶典46年3月4日所以我誤解了一些關於聲明的內容,或者我測試了一個變量是否被設置爲錯誤的方式? (我使用的信息來自How to check if a variable is set in Bash?

+0

順便說一句,'unset'有效undeclares的變量;它不只是刪除價值。 –

回答

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" 
+0

這應該工作,但不知何故,當我嘗試它在BASH 3中工作,但不是BASH4 – XSen

+0

@XSen,導出的函數不能跨越版本邊界工作(當然,不是*特定的*版本邊界;格式因shellshock而重新編譯)。因此,運行'export -f varstat'的shell需要與'bash -c'調用的版本相同。 –

+0

我只是在shell中測試「declare toto; declare -p toto」,沒有任何功能。不知何故,這不適用於4.3.46(1) - 與Ubuntu LTS 16.04一起發佈。但我已經從gnu.org下載了bash 4.4.0的源代碼,構建它並在其中嘗試了它,並且它可以正常工作....所以有一些有趣的東西與打包的版本一起進行(沒有工作在Redhat 4.1.x上工作...) – XSen