lnlidawei

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

bash:多重选择 - CASE

 

 

 

 

一、说明

 

  1、“case” 使用

 

 

 

 

二、代码

 1 [root@rocky shell]# cat mcondition 
 2 #!/usr/bin/env bash
 3 
 4 
 5 # file_name = mcondtion
 6 
 7 
 8 run()
 9 {
10         if $@
11         then
12                 echo "os_running: ${@}"
13         fi
14 }
15 
16 
17 list()
18 {
19         if  ls -lh      # command as condition of if
20         then
21                 echo
22         fi
23 }
24 
25 
26 mcondition()            #multiple condtions
27 {
28         for v in "$@"
29         do
30 
31                 case ${v} in
32 
33                         "start")
34                                 echo "command: ${v}"
35                                 ;;
36                         "stop")
37                                 echo "command: ${v}"
38                                 ;;
39                         "restart")
40                                 echo "command: ${v}"
41                                 ;;
42                         *)
43                                 echo "other_command: ${v}"
44                                 ;;
45                 esac
46 
47         done
48 }
49 
50 
51 
52 
53 mcondition $@
54 
55 [root@rocky shell]# 
56 [root@rocky shell]# 

 

 

 

 

三、运行结果

 1 [root@rocky shell]# cat mcondition 
 2 #!/usr/bin/env bash
 3 
 4 
 5 # file_name = mcondtion
 6 
 7 
 8 run()
 9 {
10         if $@
11         then
12                 echo "os_running: ${@}"
13         fi
14 }
15 
16 
17 list()
18 {
19         if  ls -lh      # command as condition of if
20         then
21                 echo
22         fi
23 }
24 
25 
26 mcondition()            #multiple condtions
27 {
28         for v in "$@"
29         do
30 
31                 case ${v} in
32 
33                         "start")
34                                 echo "command: ${v}"
35                                 ;;
36                         "stop")
37                                 echo "command: ${v}"
38                                 ;;
39                         "restart")
40                                 echo "command: ${v}"
41                                 ;;
42                         *)
43                                 echo "other_command: ${v}"
44                                 ;;
45                 esac
46 
47         done
48 }
49 
50 
51 
52 
53 mcondition $@
54 
55 [root@rocky shell]# 
56 [root@rocky shell]# 
57 [root@rocky shell]# ./mcondition start stop restart ok ls pwd
58 command: start
59 command: stop
60 command: restart
61 other_command: ok
62 other_command: ls
63 other_command: pwd
64 [root@rocky shell]# 
65 [root@rocky shell]# 

 

 

 

 

四、参考资料:

 

  1、  Conditional structures if and case:  https://docs.rockylinux.org/books/learning_bash/06-conditional-structures/

 

posted on 2023-01-29 00:31  lnlidawei  阅读(27)  评论(0编辑  收藏  举报