the case shell AND example of using case to create a menu

本文介绍了Shell脚本中case命令的基本用法及其与if/elif命令的区别。通过两个实例展示了如何使用case命令进行多分支选择,并结合heredocument创建菜单选项供用户选择。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

14.5.8 The case Command

The case command is a multiway branching command used as an alternative to if/elif commands. The value of the case variable is matched against value1, value2, and so forth, until a match is found. When a value matches the case variable, the commands following the value are executed until the double semicolons are reached. Then execution starts after the word esac (case spelled backward).

If the case variable is not matched, the program executes the commands after the *), the default value, until ;; or esac is reached. The *) value functions the same as the else statement in if/else conditionals. The case values allow the use of shell wildcards and the vertical bar (pipe symbol) for ORing two values.

FORMAT

case variable in

value1)

    command(s)

    ;;

value2)

    command(s)

    ;;

*)

command(s)

    ;;

esac


Example 14.30.
(The Script)

    #!/bin/bash

    # Scriptname: xcolors



1   echo -n "Choose a foreground color for your xterm window: "

    read color

2   case "$color" in

3   [Bb]l??)

4        xterm -fg blue -fn terminal &

5        ;;

6   [Gg]ree*)

        xterm -fg darkgreen -fn terminal &

        ;;

7   red | orange)              # The vertical bar means "or"

        xterm -fg "$color"  -fn terminal &

        ;;

8   *)

        xterm -fn terminal

        ;;

9   esac

10  echo  "Out of case command"

Creating Menus with the here document and case Command

The here document and case command are often used together. The here document is used to create a menu of choices that will be displayed to the screen. The user will be asked to select one of the menu items, and the case command will test against the set of choices to execute the appropriate command.

Example 14.31.
(From the .bash_profile File)

    echo "Select a terminal type:  "

1   cat <<- ENDIT

        1) unix

        2) xterm

        3) sun

2   ENDIT

3   read choice

4   case "$choice" in

5   1)   TERM=unix

         export TERM

         ;;

    2)   TERM=xterm

         export TERM

         ;;

6   3)   TERM=sun

         export TERM

         ;;

7   esac

8   echo "TERM is $TERM."

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值