11. 循环与分支 - 11.4 测试与分支

优质
小牛编辑
119浏览
2023-12-01

caseselect 结构并不属于循环结构,因为它们并没有反复执行代码块。但是和循环结构相似的是,它们会根据代码块顶部或尾部的条件控制程序流。

下面介绍两种在代码块中控制程序流的方法:

case (in) / esac

在 shell 脚本中,case 模拟了 C/C++ 语言中的 switch,可以根据条件跳转到其中一个分支。其相当于简写版的 if/then/else 语句。很适合用来创建菜单选项哟!

  1. case "$variable" in
  2. "$condition1" )
  3. command...
  4. ;;
  5. "$condition2" )
  6. command...
  7. ;;
  8. esac

( i386 ) echo “80386-based machine”;;
# ^ ^
( i486 ) echo “80486-based machine”;;
( i586 ) echo “Pentium-based machine”;;
( i686 ) echo “Pentium2+-based machine”;;
( * ) echo “Other type of machine”;;
esac