这段代码缺少什么?

这段代码缺少什么?

我不断收到错误 ( lab2.sh: line 7: syntax error at line 15: `)' unexpected)

#! /bin/sh

echo "M - Month of the year"

echo "S - Sleep for 10 seconds"

echo "E - Make the file executable"
echo "Please input a letter (M,S, or E): \c"

read code

case $code in

     M) date +%B ;;
     S)  sleep 10 ;;
     E) echo "ENter file name: \c"
      read fname
      chmod 755 $fname
     *)   
 echo "Error" ;;

esac

答案1

除了最后一个之外,遵循 中 模式的每组命令都case ... esac需要以 终止。;;

你应该有

M)  date +%B ;;
S)  sleep 10 ;;
E)  echo "ENter file name: \c"
    read fname
    chmod 755 "$fname" ;;
*)  echo "Error" >&2

另请注意引用$fname(以便您可以处理带有空格和特殊字符的文件名),并且诊断消息应转到标准错误(重定向到>&2)。


您也可以用于菜单,并且在文件上select运行时要更加小心:chmod

#!/bin/bash

select ch in \
    'Exit' \
    'Month of the year' \
    'Sleep for 10 seconds' \
    'Make a file executable'
do
    case $REPLY in
        1) break ;;
        2) date +'The current month is %B' ;;
        3) echo 'Sleeping for 10 seconds'
           sleep 10 ;;
        4) read -r -p 'Enter file name: ' fname
           if [ ! -f "$fname" ]; then
               printf 'No such file: %s\n' "$fname"
           else
               chmod +x "$fname"
           fi
           ;;
        *) echo 'Error' >&2
    esac
done

echo 'Bye!'

相关内容