0

I have this function in my .zshrc:

activated=false

function test_toggle() {
  if [ $activated=false ]; then
    echo "WAS FALSE"
    activated=true
  else
    echo "WAS TRUE"
    activated=false
  fi
}

I'd like the function to toggle the state of var activated between false and true. But if I open a terminal and run the function I only get this:

$ test_toggle
WAS FALSE
$ test_toggle
WAS FALSE
$ test_toggle
WAS FALSE

How can I make the function use and change the variable: activated from parent scope correctly?

Rotareti
  • 883

1 Answers1

1

I suspect the problem here is that foo=bar is assignment (same as activated=false), and the shell parser is assigning as a side-effect of the conditional. Always use [[ in ZSH code over the Bourne [, and the foo=bar should instead use spaces to distinguish the test from assignment:

activated=false
function test_toggle() {
  if [[ $activated = false ]]; then
    echo "WAS FALSE"
    activated=true
  else
    echo "WAS TRUE"
    activated=false
  fi
}

Result:

% 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
% 
thrig
  • 34,938