Shell-Script
平等檢查似乎總是正確的
我的 .zshrc 中有這個功能:
activated=false function test_toggle() { if [ $activated=false ]; then echo "WAS FALSE" activated=true else echo "WAS TRUE" activated=false fi }
我想要在和
activated
之間切換 var 狀態的函式。但是如果我打開一個終端並執行該功能,我只會得到這個:false``true
$ test_toggle WAS FALSE $ test_toggle WAS FALSE $ test_toggle WAS FALSE
如何使函式使用和更改變數:
activated
從父範圍正確?
我懷疑這裡的問題
foo=bar
是賦值(與 相同activated=false
),並且 shell 解析器將賦值作為條件的副作用。始終[[
在 ZSH 程式碼中使用 Bourne[
,並且foo=bar
應該使用空格來區分測試和賦值:activated=false function test_toggle() { if [[ $activated = false ]]; then echo "WAS FALSE" activated=true else echo "WAS TRUE" activated=false fi }
結果:
% exec zsh % which test_toggle test_toggle () { if [[ $activated = false ]] then echo "WAS FALSE" activated=true else echo "WAS TRUE" activated=false fi } % echo $activated false % test_toggle WAS FALSE % test_toggle WAS TRUE % test_toggle WAS FALSE %