case 命令 case语句与if-then-else语句的区别。 例1:if-then-else语句,比较繁琐 [19:37:32 root@libin3 libin]# usermod -G root student [19:22:33 root@libin3 libin]# vim shell55 [19:37:32 root@libin3 libin]# cat shell55 #!/bin/bash # look for a value # if [ $USER = root ] then echo "the user is root" elif [ $USER = student ] then echo "the user is student" elif [ $USER = rhce ] then echo "the user is student" elif [ $USER = helloword ] then echo "the user is helloword" else echo "sorry,no a user exist" fi [19:26:24 root@libin3 libin]# chmod u+x shell55 [19:26:31 root@libin3 libin]# ./shell55 the user is root [student@libin3 libin]$ sudo chmod g+x shell55 [student@libin3 libin]$ ./shell55 the user is student case命令,就不需要写elif语句检查同一个变量值。case命令会采用下面的列表格式来检查单个变量的多个值。 格式: case variable in pattern1 | pattern2) commands1;; pattern3) commands2;; *) default commands;; esac case命令会将指定的变量与不同模式进行比较。如果变量和模式是匹配的,那么shell会执行 为该模式指定的命令。通过 | 操作符在一行中分隔出多各模式。 * 号会捕获所有与已知模式不匹配的值,就相当于else。 例2:将例1的语句转换成case语句 示例1: [19:48:36 root@libin3 libin]# vim shell56 #!/bin/bash #using the case command # case $USER in root | student) echo "the is $USER";; rhce) echo "the is rhce";; student) echo "the is student";; helloword) echo "the is helloword";; *) echo "no is user";; esac [19:52:16 root@libin3 libin]# chmod +x shell56 [19:53:11 root@libin3 libin]# ./shell56 the is root 示例2: [19:56:00 root@libin3 libin]# su - student [student@libin3 libin]$ sudo chmod g+x /libin/libin/shell56 [student@libin3 libin]$ ./shell56 the is student 例3:这里我们可以得出case语句判断出了libin3.com 为主机名 [21:11:43 root@libin3 libin]# echo $HOSTNAME libin3.com [21:11:45 root@libin3 libin]# vim shell57 #!/bin/bash # using the case command # case $HOSTNAME in libin2.com | libin4.com ) echo "the is $HOSTNAME";; libin5.com | libin3.com ) echo "the hostname is libin5.com or $HOSTNAME";; libin6.com) echo "the hostname is libin6.com";; *) echo "no HOSTNAME";; esac [21:04:47 root@libin3 libin]# chmod u+x shell57 [21:05:02 root@libin3 libin]# ./shell57 the hostname is libin5.com or libin3.com
标签:case,语句,libin3,echo,student,Linux,libin,root From: https://www.cnblogs.com/libin-linux/p/16609062.html