Shell脚本中Case分支嵌套If-else的语法错误排查求助
Shell脚本语法错误排查:Case分支嵌套If-else报错";; unexpected (expecting fi)"
编写的Shell脚本包含Case语句,且在c分支中嵌套了If-else逻辑,选择选项c时触发语法错误,报错信息如下:
./a.sh: 27: Syntax error: ";;" unexpected (expecting "fi")
原脚本
#!/bin/sh echo Enter choice : echo a : To create a file, name given by user. echo b : To copy file to another location. echo c : To determine minimum age to vote. read choice case $choice in a) echo Enter the name of file. read name mkdir $name ;; b) echo Enter file name you want to copy read file_name echo Enter location where you want to copy $file_name read location cp -r $file_name "$location";; c) echo Enter age : read age if [ age -ge 18 ] then echo You are eligible else echo You are not eligible "fi" ;; *) echo Please! Enter correct choice. esac
错误输出
Enter choice : a : To create a file, name given by user. b : To copy file to another location. c : To determine minimum age to vote. c ./a.sh: 27: Syntax error: ";;" unexpected (expecting "fi")
问题原因及修复
- If语句结束关键字错误:c分支中的
"fi"被加了双引号,Shell会将其视为字符串命令而非结束if的关键字,导致if语句未正确闭合,后续的;;触发语法错误。需去掉引号,直接写fi。 - 变量引用错误:
if [ age -ge 18 ]中直接写age会被当成字符串字面量,无法读取输入的年龄变量,应改为$age来引用变量。
修正后的完整脚本
#!/bin/sh echo Enter choice : echo a : To create a file, name given by user. echo b : To copy file to another location. echo c : To determine minimum age to vote. read choice case $choice in a) echo Enter the name of file. read name mkdir $name ;; b) echo Enter file name you want to copy read file_name echo Enter location where you want to copy $file_name read location cp -r $file_name "$location";; c) echo Enter age : read age if [ $age -ge 18 ] then echo You are eligible else echo You are not eligible fi ;; *) echo Please! Enter correct choice. esac
内容的提问来源于stack exchange,提问作者Satendra Patel
相关产品推荐
相关产品推荐

