bash 嵌套 if/else 的 zsh 脚本解析器错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39999237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 15:17:56  来源:igfitidea点击:

zsh script parser error for nested if/else

bashscriptingzsh

提问by George H

I have the following humble zsh function:

我有以下不起眼的 zsh 功能:

function remember()
{
  if [ "" != "" ]
  then
    if[ "" != "clean" ]
    then
      echo "Why";
      #echo  >> {~/.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";)

`echo' 附近的解析错误(回声是带有回声“为什么”的那一行;)

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)

有没有办法“调试”这种事情?zsh -n 没有太大帮助(根本)

回答by chepner

You forgot the space between ifand [when comparing to clean.

if[相比时,您忘记了和之间的空格clean

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

但是,在这种情况下,您可以通过=首先处理案例来简化您的功能。

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

Or, use a casestatement.

或者,使用case语句。

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

回答by Arkadiusz Drabczyk

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

之后缺少空格[。它应该是:

function remember()
{
    if [ "" != "" ]
    then
    if [ "" != "clean" ]
    then
        echo "Why";
        #echo  >> {~/.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。它是一个单独的命令,描述man test如下:

TEST(1)                                                                                                                          

NAME
       test - check file types and compare values

SYNOPSIS
       test EXPRESSION
       test

       [ EXPRESSION ]
       [ ]
       [ OPTION