Shell-Script

平等檢查似乎總是正確的

  • November 7, 2018

我的 .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
% 

引用自:https://unix.stackexchange.com/questions/327187