【问题标题】:Switch case: Confusing error in "Syntax error: word unexpected (expecting "in")"切换案例:“语法错误:单词意外(期望“in”)”中的令人困惑的错误
【发布时间】:2015-02-08 22:07:10
【问题描述】:

这是我的代码:

echo
echo "WELCOME"
echo "-------------------------------------------------"
while true
do
  echo
  echo "Select A Menu Option"
  echo "1: Ancestry History"
  echo "2: Who is Online"
  echo "3: What Process Any User is Running"
  echo "4: Exit"
  read mOption
  case $mOption in

  1)  echo
      echo "The Ancestry Tree For Current Process is....";
      ps -ef > processes
      grep "ps -ef" processes > grepProcesses
      awk '{print $2, $3}' processes > awkProcesses
      PID=$(awk '{print $2}' grepProcesses)
      echo $PID
      SPID=$(awk '{print $3}' grepProcesses)
      PID=$SPID
      end=0
      while [ $end != 1 ]
      do
        echo " | "
        echo $SPID
        PID=$SPID
        SPID=$(grep ^"$PID " awkProcesses | cut -d' ' -f2)
        if [ "$PID" = "1" ]
          then
          end=1
        fi
      done

      rm processes
      rm grepProcesses
      rm awkProcesses
      ;;

  2)  echo 
      echo "Users Currently Online";
      who | cut -d' ' -f1
      ;;

  3)  echo
      echo "Select a Currently Online User to View their Processes:"
      index=0
      who | while read onlineUser
            do 
              echo "$index-$onlineUser" who|cut -d' ' -f1>>userList
              index=$((index+1))
            done
            awk '{ print $0 }' userList
            read choice
            if [ $choice ]
            then
              echo
              echo ***Process Currently Running***
              person=$(grep ^$choice userList |cut -d'-' -f2)
          ps -ef >> process
          grep $person process
        else
          echo You have made a mistake. Please start over.
        fi
        rm userList
        rm process
        ;;

  4)  echo
      echo "Exiting..."
      exit 1;;

  *)  
      echo
      echo "Invalid Input. Try Again."
      ;;
  esac

done

每次运行它时,我都会不断收到语法错误“hmwk1.sh: 17: hmwk1.sh: Syntax error: word unexpected (expecting "in")” 我查找了不同的语法示例,看来我的代码看起来是正确的。但是我的反复试验让我无法修复我的代码。

我可能缺少某种括号或引号吗?

【问题讨论】:

  • 你在什么样的外壳上运行它?尝试在脚本顶部添加#!/bin/bash?
  • 在 bash 上为我工作。你是如何运行它的?
  • 它也对我有用,但我们从这里复制它,请检查您的文件是否有 dos ^M 并将新行转换为 unix 格式。
  • 在 bash 中也适用于我
  • 我在顶部有 #!/bin/bash,我忘记将它包含在此代码中,但现在已修复。

标签: linux bash shell


【解决方案1】:

如果你只是在提示符下按回车

 read mOption
 case $mOption in

那么 $mOption 是一个空标记,让 shell 只看到

case in

这是一个语法错误。如果你添加

test -z "$mOption" && continue

在中间,如果会修复那个问题。

【讨论】:

  • 谢谢!这解决了它!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-21
  • 1970-01-01
  • 2012-05-19
  • 2017-01-26
  • 1970-01-01
  • 2018-03-14
  • 1970-01-01
相关资源
最近更新 更多