我想知道如何聲明一個變量而不向它賦值。據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?)
順便說一句,'unset'有效undeclares的變量;它不只是刪除價值。 –