Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

zsh script parser error for nested if/else

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)

like image 358
George H Avatar asked Oct 12 '16 12:10

George H


2 Answers

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
}
like image 50
chepner Avatar answered Sep 30 '22 05:09

chepner


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
like image 31
Arkadiusz Drabczyk Avatar answered Sep 30 '22 05:09

Arkadiusz Drabczyk