我的 .zshrc 中有这个函数:
activated=false
function test_toggle() {
if [ $activated=false ]; then
echo "WAS FALSE"
activated=true
else
echo "WAS TRUE"
activated=false
fi
}
activated
我希望该函数能够在false
和之间切换 var 的状态true
。但是,如果我打开终端并运行该函数,我只会得到以下结果:
$ test_toggle
WAS FALSE
$ test_toggle
WAS FALSE
$ test_toggle
WAS FALSE
如何使函数activated
正确使用和更改父作用域中的变量:?
答案1
我怀疑这里的问题是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
%