zsh script parser error for nested if/else

26,585

Solution 1

You forgot the space between if and [ when comparing to clean.

This is case, though, where your function can be made simpler by handling the = case first.

function remember()
{
  if [ "$1" = "" ]; then
    cat ~/.remember_info
  elif [ "$1" = clean ]; then
    rm -r ~/.remember_info
    touch ~/.remember_info
  else
    echo "$1" >> ~/.remember_info;
  fi
}

Or, use a case statement.

remember () {
  f=~/.remember_info
  case $1 of
    "")
      cat "$f"
      ;;
    clean)
      rm -r "$f"
      touch "$f"
      ;;
    *)
      print "$1" >> "$f"
      ;;
  esac
}

Solution 2

You are missing a whitespace after [. It should be:

function remember()
{
    if [ "$1" != "" ]
    then
    if [ "$1" != "clean" ]
    then
        echo "Why";
        #echo $1 >> {~/.remember_info};
    else
        rm -r ~/.remember_info;
        touch ~/.remember_info;
    fi
    else
    cat .remember_info;
    fi
}

[ is the same as test. It is a separate command, described in man test:

TEST(1)                                                                                                                          

NAME
       test - check file types and compare values

SYNOPSIS
       test EXPRESSION
       test

       [ EXPRESSION ]
       [ ]
       [ OPTION
Share:
26,585
George H
Author by

George H

Updated on October 13, 2020

Comments

  • George H
    George H over 3 years

    I have the following humble zsh function:

    function remember()
    {
      if [ "$1" != "" ]
      then
        if[ "$1" != "clean" ]
        then
          echo "Why";
          #echo $1 >> {~/.remember_info};
        else
          rm -r ~/.remember_info;
          touch ~/.remember_info;
        fi
      else
        cat .remember_info;
      fi
    }
    

    When I try to source it I get:

    parse error near `echo' (The echo being the line with echo "Why";)

    The error is quite non descriptive and I assume its related to part of the loop's logic (since no matter what instruction I give after then it error out there).

    Is there any way to "debug" this kind of thing ? zsh -n doesn't help much (at all)