【问题标题】:While loop in BASH script causing syntax errorBASH脚本中的while循环导致语法错误
【发布时间】:2018-06-28 16:44:46
【问题描述】:

我最近开始编写 BASH 脚本,目前正在尝试使用 while 循环。但是,当我运行以下代码块时,命令提示符会响应:

run.command: line 12: syntax error near unexpected token `done'
run.command: `done'

然后程序关闭。 这是我正在运行的代码。

#!/bin/bash
echo -e "text"
c=false
while true; do
    printf ">> "
    i=read 
    if [$i = "exit"]; then
        exit
    else if [$i = "no"]; then
        echo "no"
    else
        echo -e "Error: $i is undefined"
    fi
done

我对 while 循环进行了一些研究,但我的循环语法似乎是正确的。当我在最后删除完成时,会发生Unexpected end of file 错误。任何帮助将不胜感激!

【问题讨论】:

标签: bash


【解决方案1】:

您可以使用-p 选项读取提示和case ... esac 构造:

while true; do
  read -r -p ">> " i
  case "$i" in
     "exit") exit 0  ;;
     "no") echo "no" ;;
     *) echo -e "Error: $i is undefined";;
  esac
done

【讨论】:

  • 谢谢!我会对此进行更多研究。
【解决方案2】:

我自己修好了!

#!/bin/bash
echo -e "text"
c=false
while true; do
  printf ">> "
  read i
  if [ "$i" = "exit" ]; then
    exit
  elif [ "$i" = "no" ]; then
     echo "no"
  else
     echo -e "Error: $i is undefined"
  fi
done

【讨论】:

  • 您应该引用$i,以避免来自[ 的“参数过多”错误。
  • 说明:用an input with two or more words测试。你可以使用"$i"
  • 感谢您的提示!还有什么我可以改进的地方吗?
  • @Jerrybibo,实际上最好避免使用echo -e:支持该选项在输出上执行除打印-e 之外的任何操作与echo 的POSIX 规范背道而驰。如果您想要格式字符串支持,请使用printf
  • @Jerrybibo, ...有关上述规范,请参阅pubs.opengroup.org/onlinepubs/009604599/utilities/echo.html(并注意所有警告:在POSIX echo中未定义带有any反斜杠的字符串时的行为;给定-n 时的行为未定义;给定-e 时的行为定义,但定义为要求在输出上打印-e;等等)。
猜你喜欢
  • 1970-01-01
  • 2017-04-17
  • 2017-01-15
  • 2013-12-21
  • 2014-10-04
  • 1970-01-01
  • 2010-10-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多