开发者问题收集

Bash 脚本 switch case 时出错

2016-12-06
571

我想创建一个简单的巫术案例,在其中我可以根据用户提示执行函数:

echo Would you like us to perform the option: "(Y|N)"

read inPut

case $inPut in
# echoing a command encapsulated by
# backticks (``) executes the command
"Y") echo 'Starting.....'
donwload_source_code


# depending on the scenario, execute the other option
# or leave as default
"N") echo 'Stopping execution'
exit
esac

但是当我执行脚本时出现错误:

Would you like us to perform the option: (Y|N)
n
run.sh: line 27: syntax error near unexpected token `)'
run.sh: line 27: `"N") echo 'Stopping execution''
EMP-SOF-LT099:Genesis Plamen$ 

您知道如何解决这个问题吗?

2个回答

多个问题。

  1. 在每个 case 构造末尾添加 ;;
  2. exit 命令在 switch-case 构造中放置错误,没有 ;; 。它应该在 case 末尾或上方。
  3. read 有自己的选项来打印用户提示消息,可以避免不必要的 echo

无错误脚本

#!/bin/bash

read -p "Would you like us to perform the option: \"(Y|N)\" " inPut

case $inPut in
# echoing a command encapsulated by
# backticks (``) executes the command
"Y") echo 'Starting.....'
donwload_source_code
;;


# depending on the scenario, execute the other option
# or leave as default
"N") echo 'Stopping execution'
exit
;;

esac
Inian
2016-12-06

添加 ;;

#!/bin/bash
echo Would you like us to perform the option: "(Y|N)"

read inPut

case $inPut in
# echoing a command encapsulated by
# backticks (``) executes the command
"Y") echo 'Starting.....'
donwload_source_code


# depending on the scenario, execute the other option
# or leave as default
;;
"N") echo 'Stopping execution'
exit
;;
esac
LF-DevJourney
2016-12-06