美文网首页
11 - shell之case语句

11 - shell之case语句

作者: 舍是境界 | 来源:发表于2022-03-23 06:57 被阅读0次

case语法格式

  • 检查、判断变量的取值
    • 效果类似于多分支的if语句
    • 如果与预设的值相匹配,则执行相应的操作
    • 命令序列最后必须以分号结尾
case 变量 in
模式1)
  命令序列1;;
模式2)
  命令序列2;;
... ...
*)
  默认命令序列
esac

case范例

  • 判断用户的输入
#!/bin/bash
read -p "请输入redhat|fedora:" key
case $key in
redhat)
  echo "fedora.";;
fedora)
  echo "redhat.";;
*)
  echo "必须输入redhat或fedora."
esac
  • 判断用户的输入
#!/bin/bash
read -p "Are you sure?[y/n]:" sure
case $sure in
y|Y|yes|YES)
  echo "you enter $sure, OK";;
n|N|no|NO)
  echo "you enter $sure,OVER";;
*)
  echo "error";;
esac

数组

  • 数组也是一个变量,是一个有点特殊的变量
  • 存储多个数据的集合就是数组
test=(11 22 33)
echo ${test[0]}
11

echo ${test[1]}
22

  • 石头剪刀布游戏
#!/bin/bash
game=(stone scissor cloth)
num=$[RANDOM%3]
computer=${game[$num]}
#通过随机数获取计算机的出拳
#出拳的可能性保存在一个数组中:game[0],game[1],game[2]
echo "请根据下列提示选择您的出拳手势"
echo "1.stone 石头"
echo "2.scissor 剪刀"
echo "3.cloth 布"

read -p "请选择1-3:" person
case $person in
1)
  if [ $num -eq 0 ];then
    echo "平局"
  elif [ $num -eq 1 ];then
    echo "你赢"
  else
    echo "计算机赢"
  fi;;
2)
  if [ $num -eq 1 ];then
    echo "平局"
  elif [ $num -eq 2 ];then
    echo "你赢"
  else
    echo "计算机赢"
  fi;;
3)
  if [ $num -eq 2 ];then
    echo "平局"
  elif [ $num -eq 0 ];then
    echo "你赢"
  else
    echo "计算机赢"
  fi;;
*)
  echo "输入非法,OVER"
esac

小结

  • case语法
  • 案例
    • 判断用户的输入信息
    • 石头剪刀布游戏

相关文章

  • Shell 流程控制

    case语句 Shell case语句为多选择语句。 输出 while语句 输出 Shell 双括号运算符

  • 11 - shell之case语句

    case语法格式 检查、判断变量的取值效果类似于多分支的if语句如果与预设的值相匹配,则执行相应的操作命令序列最后...

  • Shell编程之case流程控制语句

    Shell之case语句 1.case 用来实现对程序流程的选择、循环等进行控制。 语法: case 变量 in ...

  • shell 笔记 Day03

    shell 笔记 Day03 case语句:case 变量 in模式1)语句;;模式2)语句;;*)默认语句esa...

  • linux学习--week19--shell

    4天 Shell脚本大纲1.shell介绍2.shell变量3.shell 判断语句 if case gitjen...

  • shell流程控制-case条件判断语句

    case多条件分支语句case介绍case语法shell特殊变量一、case介绍在生产环境中,我们总会遇到一个问题...

  • Shell case esac语句

    case ... esac 与其他语言中的 switch ... case 语句类似,是一种多分枝选择结构。 ca...

  • Shell | case 条件语句

    case 条件语句语法: case "变量" in 值 1 ) ##变量为值...

  • linux bash Shell case

    Shell case语句为多选择语句。可以用case语句匹配一个值与一个模式,如果匹配成功,执行相匹配的命令。ca...

  • JavaScript 填坑专集

    条件语句之switch-case-break switch语句中的case比较是严格相等运算(===),而不是普通...

网友评论

      本文标题:11 - shell之case语句

      本文链接:https://www.haomeiwen.com/subject/cgkudrtx.html