[英]Testing to see if an env variable is set in bash
在bash腳本中,我試圖測試變量的存在。 但無論我做什么,我的“if”測試都會返回true。 這是代碼:
ignored-deps-are-not-set () {
if [ -z "${ignored_deps+x}" ]
then
return 0
fi
return 1
}
ignored_deps=1
ignored-deps-are-not-set
echo "ignored-deps function returns: $?"
if [ ignored-deps-are-not-set ]
then
echo "variable is unset"
else
echo "variable exists"
fi
這是寫的輸出:
ignored-deps function returns: 1
variable is unset
當我注釋掉設置了ignored_deps的行時的輸出。
ignored-deps function returns: 0
variable is unset
無論怎樣,它都說這個變量沒有設置。 我錯過了什么?
這一行:
if [ ignored-deps-are-not-set ]
測試字符串'ignored-deps-not-set-set'是否為空。 它返回true,因為該字符串不為空。 它不執行命令(因此也不執行函數)。
如果要測試是否設置了變量,請使用${variable:xxxx}
表示法之一。
if [ ${ignored_deps+x} ]
then echo "ignored_deps is set ($ignored_deps)"
else echo "ignored_deps is not set"
fi
在${ignored_deps+x}
符號計算為x
,如果$ignored_deps
設置,即使它被設置為空字符串。 如果您只想將它設置為非空值,那么也使用冒號:
if [ ${ignored_deps:+x} ]
then echo "ignored_deps is set ($ignored_deps)"
else echo "ignored_deps is not set or is empty"
fi
如果要執行該函數(假設破折號在函數名中起作用),則:
if ignored-deps-are-not-set
then echo "Function returned a zero (success) status"
else echo "Function returned a non-zero (failure) status"
fi
你實際上並沒有執行這個功能:
if ignored-deps-are-not-set; then ...
使用[]
括號,文字字符串“ignored-deps-not-set-set”被視為true。
if [ ${myvar:-notset} -eq "notset" ] then
...
--edit--剛剛意識到這是一個函數,它試圖調用,約定是錯誤的。
看到:
Z000DGQD@CND131D5W6 ~
$ function a-b-c() {
> return 1
> }
Z000DGQD@CND131D5W6 ~
$ a-b-c
Z000DGQD@CND131D5W6 ~
$ echo $?
1
Z000DGQD@CND131D5W6 ~
$ if a-b-c; then echo hi; else echo ho; fi
ho
Z000DGQD@CND131D5W6 ~
$ if [ a-b-c ]; then echo hi; else echo ho; fi
hi
Z000DGQD@CND131D5W6 ~
- 編輯結束 -
修復變量名稱(請參閱我對您帖子的評論)
然后
請參閱man bash
參數擴展部分。
${parameter:?word}:
如果為空或未設置則顯示錯誤。 如果參數為null或未設置,則單詞的擴展(或者如果單詞不存在則為該效果的消息)將寫入標准錯誤,並且如果shell不是交互式,則退出。 否則,參數的值將被替換。
另一種測試變量存在的方法:
if compgen -A variable test_existence_of_var; then
echo yes
else
echo no
fi
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.