SHELL脚本编程条件选择(if语句)和条件判断(case语句)
SHELL脚本编程条件选择(if语句)和条件判断(case语句)
作者:尹正杰
版权声明:原创作品,谢绝转载!否则将追究法律责任。
一.条件选择if语句
[root@node101.yinzhengjie.org.cn ~]# help if if: if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ else COMMANDS; ] fi Execute commands based on conditional. The `if COMMANDS' list is executed. If its exit status is zero, then the `then COMMANDS' list is executed. Otherwise, each `elif COMMANDS' list is executed in turn, and if its exit status is zero, the corresponding `then COMMANDS' list is executed and the if command completes. Otherwise, the `else COMMANDS' list is executed, if present. The exit status of the entire construct is the exit status of the last command executed, or zero if no condition tested true. Exit Status: Returns the status of the last command executed. [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]#
1>.单分支if语句
语法格式一(推荐) if [ 条件测试表达式 ];then 源代码 fi 语法格式二 if [ 条件测试表达式 ] then 源代码 fi 温馨提示: 条件选择语句顾名思义就是根据条件测试表达式是否为true选择执行。 if语句可嵌套。 if语句使用fi结尾,和一般语言使用大括号结尾不同; [ 条件测试表达式 ]就是使用test命令测试,所以中括号和条件判断式之间必须有空格; then后面跟符合条件之后执行的程序,可以放在[]之后,用";"分割。也可以换行写入,就不需要";"啦;
[root@node101.yinzhengjie.org.cn ~]# vim shell/partitions.sh #编写一个监控boot分区的脚本 [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# cat shell/partitions.sh #!/bin/bash # #******************************************************************** #Author: yinzhengjie #QQ: 1053419035 #Date: 2019-11-23 #FileName: shell/partitions.sh #URL: http://www.cnblogs.com/yinzhengjie #Description: The test script #Copyright notice: original works, no reprint! Otherwise, legal liability will be investigated. #******************************************************************** res=$(df -h | grep "/dev/sda1" | awk '{print $5}'| cut -d "%" -f1) if [ $res -ge 80 ] then echo "Warning! /dev/sda2 is full!!!" fi [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# chmod +x shell/partitions.sh [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# ll shell/partitions.sh -rwxr-xr-x 1 root root 617 Nov 23 04:51 shell/partitions.sh [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# df -h Filesystem Size Used Avail Use% Mounted on /dev/mapper/centos-root 50G 1.5G 49G 3% / devtmpfs 3.9G 0 3.9G 0% /dev tmpfs 3.9G 0 3.9G 0% /dev/shm tmpfs 3.9G 8.6M 3.9G 1% /run tmpfs 3.9G 0 3.9G 0% /sys/fs/cgroup /dev/sda1 1014M 146M 869M 15% /boot /dev/mapper/centos-home 941G 3.0G 938G 1% /home tmpfs 783M 0 783M 0% /run/user/0 [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# ./shell/partitions.sh [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# dd if=/dev/zero of=/boot/bigfile bs=1M count=800 #为了达到测试效果,为我们可以把在"/boot"分区里写入一个大文件从而达到快速达到脚本报警阈值。 800+0 records in 800+0 records out 838860800 bytes (839 MB) copied, 1.78826 s, 469 MB/s [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# df -h Filesystem Size Used Avail Use% Mounted on /dev/mapper/centos-root 50G 1.5G 49G 3% / devtmpfs 3.9G 0 3.9G 0% /dev tmpfs 3.9G 0 3.9G 0% /dev/shm tmpfs 3.9G 8.6M 3.9G 1% /run tmpfs 3.9G 0 3.9G 0% /sys/fs/cgroup /dev/sda1 1014M 948M 67M 94% /boot /dev/mapper/centos-home 941G 3.0G 938G 1% /home tmpfs 783M 0 783M 0% /run/user/0 [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# ./shell/partitions.sh Warning! /dev/sda2 is full!!! [root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# declare -f | grep if #不难发现系统中定义的脚本也有很多if嵌套使用案例 if [[ ${!1} == \~* ]]; then if [[ ${!1} == */* ]]; then if [[ $index -gt 0 && ( -n $lead && -n ${lead//[[:space:]]} ) ]]; then if [[ $i -lt $cword ]]; then if [[ "$1" == *:* && "$COMP_WORDBREAKS" == *:* ]]; then if [[ $option =~ (\[((no|dont)-?)\]). ]]; then if [[ -n $1 ]]; then if [[ -n $exclude ]]; then if _complete_as_root; then if _complete_as_root; then if [[ ${1:-} == -w ]]; then if [[ ${1:-} == -a ]]; then cmd="{ ifconfig || ip link show up; }"; cmd="{ ifconfig -a || ip link show; }"; COMPREPLY=($( eval $cmd 2>/dev/null | awk '/^[^ \t]/ { if ($1 ~ /^[0-9]+:/) { print $2 } else { prin t $1 } }' )); if [[ -z "${CDPATH:-}" || "$cur" == ?(.)?(.)/* ]]; then if [[ ( -n $mark_symdirs && -h $j || -n $mark_dirs && ! -h $j ) && ! -d ${j#$i/} ]]; then if [[ ${#COMPREPLY[@]} -eq 1 ]]; then if [[ "$i" == "$cur" && $i != "*/" ]]; then if [[ "${COMP_WORDS[i]}" != -* ]]; then if [[ $COMP_CWORD -eq 0 ]]; then if [[ ! -n $cspec && $cmd == */* ]]; then if [[ ! -n $cspec ]]; then if [[ -n $cspec ]]; then if [[ ${cspec#* -F } != $cspec ]]; then if [[ ${#COMP_WORDS[@]} -ge 2 ]]; then if [[ ${#COMPREPLY[@]} -eq 0 ]]; then if [[ -f /etc/debian_version ]]; then COMPREPLY=($( compgen -W "$( sed -ne 's|^iface \([^ ]\{1,\}\).*$|\1|p' /etc/network/interface s )" -- "$cur" )); if [[ -f /etc/SuSE-release ]]; then COMPREPLY=($( compgen -W "$( printf '%s\n' /etc/sysconfig/network/ifcfg-* | sed -ne 's|.*ifcfg-\(.*\)|\1|p' )" -- "$cur" )); if [[ -f /etc/pld-release ]]; then COMPREPLY=($( compgen -W "$( command ls -B /etc/sysconfig/interfaces | s ed -ne 's|.*ifcfg-\(.*\)|\1|p' )" -- "$cur" )); COMPREPLY=($( compgen -W "$( printf '%s\n' /etc/sysconfig/network-scripts/ifcfg-* | sed -ne 's|.*ifcfg-\(.*\)|\1|p' )" -- "$cur" )); if [[ "$cur" == \~*/* ]]; then if [[ "$cur" == \~* ]]; then if [[ "$1" != -d ]]; then if [[ ${#toks[@]} -ne 0 ]]; then if [[ $xspec == !* ]]; then if [[ ${#toks[@]} -ne 0 ]]; then if [[ -e /proc/filesystems ]]; then if [[ -n ${2//[^0-9]/} ]]; then if [[ "${#words[cword]}" -eq 0 || "$COMP_POINT" == "${#COMP_LINE}" ]]; then if [[ "$i" -lt "$cword" ]]; then if [[ "${words[cword]:0:${#cur}}" != "$cur" ]]; then if [[ "${COMP_WORDS[i]}" != -* ]]; then if [[ $COMP_CWORD -ge 1 ]]; then if type getent &>/dev/null; then if type perl &>/dev/null; then if [[ $cur == $redir* || $prev == $redir ]]; then if [[ ${words[i]} == $redir* ]]; then COMPREPLY=($( compgen -W "$( PATH="$PATH:/sbin" lsmod | awk '{if (NR != 1) print $1}' )" -- "$1" )) COMPREPLY+=($( compgen -W "$( { LC_ALL=C ifconfig -a || ip addr show; } 2>/dev/null | [[ $# -ge $OPTIND ]] && echo "error: $FUNCNAME("$@"): unprocessed arguments:" $(while [[ $# -ge $OPTIND ]]; do printf '%s\n' ${!OPTIND}; shift; done); if [[ -n $configfile ]]; then if [[ ${#config[@]} -gt 0 ]]; then if [[ -z $configfile ]]; then if [[ ${#kh[@]} -gt 0 || ${#khd[@]} -gt 0 ]]; then if [[ "$awkcur" == [0-9]*[.:]* ]]; then if [[ "$awkcur" == [0-9]* ]]; then if [[ -z $awkcur ]]; then if [[ ${#kh[@]} -gt 0 ]]; then if ($i !~ /[*?]/ && $i ~ /'"$awkcur"'/) {print $i} \ if [[ ${#khd[@]} -gt 0 ]]; then if [[ "$i" == *key_22_$curd*.pub && -r "$i" ]]; then if [[ ${#config[@]} -gt 0 && -n "$aliases" ]]; then if [[ -n ${COMP_KNOWN_HOSTS_WITH_AVAHI:-} ]] && type avahi-browse &>/dev/null; then if [[ -n ${COMP_KNOWN_HOSTS_WITH_HOSTFILE-1} ]]; then if [[ "$cur" == -* ]]; then if [[ "$1" == @(mk|rm)dir ]]; then COMPREPLY+=($( { ifconfig -a || ip link show; } 2>/dev/null | sed -ne "s/.*[[:space:]]HWaddr[[:space :]]\{1,\}\($re\)[[:space:]].*/\1/p" -ne "s/.*[[:space:]]HWaddr[[:space:]]\{1,\}\($re\)[[:space:]]*$/\1/p" -ne "s|.*[[:space:]]\(link/\)\{0,1\}ether[[:space:]]\{1,\}\($re\)[[:space:]].*|\2|p" -ne "s|.*[[:space:]]\(link/\)\{0,1\}ether[[:space:]]\{1,\}\($re\)[[:space:]]*$|\2|p" if [[ $1 == \'* ]]; then if type -p realpath > /dev/null; then if type -p greadlink > /dev/null; then if type -p readlink > /dev/null; then if [[ $cword -eq 1 && $prev == ?(*/)service ]]; then if [[ "$cur" == --?*=* ]]; then if [[ $1 == \~* && $1 != */* ]]; then if type getent &>/dev/null; then if type perl &>/dev/null; then if unset -v "$1"; then if (( $# == 2 )); then if ! (( $# )); then echo "bash: ${FUNCNAME[0]}: \`$1': missing" "number specifier" 1>&2; echo "bash:" "${FUNCNAME[0]}: \`$1': invalid number specifier" 1>&2; [[ -n "$2" ]] && unset -v "$2" && eval $2=\(\"\${@:3:${1#-a}}\"\) && shift $((${1#-a} + 2)) || { [[ -n "$2" ]] && unset -v "$2" && eval $2=\"\$3\" && shift 3 || { if [[ $cur == *@* ]]; then if [[ $cur = *\\\\* || $cur = *:*:* ]]; then if [[ $cur = *\\:* ]]; then if [[ $1 == -u ]]; then if [[ $cur = *:* ]]; then if [[ $1 == -u ]]; then if [[ $1 == -u ]]; then if [[ $cur =~ ^(\$\{?)([A-Za-z0-9_]*)$ ]]; then shift; if [[ -d $xinetddir ]]; then [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]#
2>.双分支if语句
if [ 条件测试表达式 ] then 条件成立时,执行的源代码。 else 条件不成立时,执行的另一个程序。 fi
[root@node101.yinzhengjie.org.cn ~]# vim shell/file_backup.sh #备份服务器的某个目录 [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# ll total 0 drwxr-xr-x 2 root root 208 Nov 23 07:23 shell [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# cat shell/file_backup.sh #!/bin/bash # #******************************************************************** #Author: yinzhengjie #QQ: 1053419035 #Date: 2019-11-23 #FileName: shell/file_backup.sh #URL: http://www.cnblogs.com/yinzhengjie #Description: The test script #Copyright notice: original works, no reprint! Otherwise, legal liability will be investigated. #******************************************************************** #同步系统时间,可以先ping通再选择服务器,1.cn.pool.ntp.org;2.asia.pool.ntp.org;3.asia.pool.ntp.org ntpdate 2.asia.pool.ntp.org &> /dev/null FilePath="/boot" BackSave="/root/backup" date=`date +%F` size=$(du -sh $FilePath) filename=boot_${date}.tar.gz if [ -d $BackSave ] then usleep 10 else mkdir $BackSave fi echo "Date is:$date" > ${BackSave}/backup.log echo "Size is:$size" >> ${BackSave}/backup.log tar -zcf ${BackSave}/${filename} ${FilePath} ${BackSave}/backup.log &> /dev/null rm -f ${BackSave}/backup.log [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# bash shell/file_backup.sh [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# ll total 0 drwxr-xr-x 2 root root 36 Nov 23 07:23 backup drwxr-xr-x 2 root root 208 Nov 23 07:23 shell [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# cd backup/ [root@node101.yinzhengjie.org.cn ~/backup]# [root@node101.yinzhengjie.org.cn ~/backup]# ll total 106008 -rw-r--r-- 1 root root 108548748 Nov 23 07:23 boot_2019-11-23.tar.gz [root@node101.yinzhengjie.org.cn ~/backup]# [root@node101.yinzhengjie.org.cn ~/backup]# tar zxf boot_2019-11-23.tar.gz [root@node101.yinzhengjie.org.cn ~/backup]# ll total 106012 dr-xr-xr-x 5 root root 4096 Nov 23 07:16 boot -rw-r--r-- 1 root root 108548748 Nov 23 07:23 boot_2019-11-23.tar.gz drwxr-xr-x 3 root root 20 Nov 23 07:24 root [root@node101.yinzhengjie.org.cn ~/backup]# [root@node101.yinzhengjie.org.cn ~/backup]# cat root/backup/backup.log Date is:2019-11-23 Size is:113M /boot [root@node101.yinzhengjie.org.cn ~/backup]# [root@node101.yinzhengjie.org.cn ~/backup]# ll boot total 107232 -rw-r--r-- 1 root root 151918 Nov 9 2018 config-3.10.0-957.el7.x86_64 drwxr-xr-x 3 root root 17 Jul 8 16:22 efi drwxr-xr-x 2 root root 27 Jul 8 16:23 grub drwx------ 5 root root 97 Jul 8 16:25 grub2 -rw------- 1 root root 57158964 Jul 8 16:24 initramfs-0-rescue-9ccdf621e5984f3b8626614f6fa15a48.img -rw------- 1 root root 21752722 Jul 8 16:25 initramfs-3.10.0-957.el7.x86_64.img -rw------- 1 root root 13584214 Jul 9 10:49 initramfs-3.10.0-957.el7.x86_64kdump.img -rw-r--r-- 1 root root 314036 Nov 9 2018 symvers-3.10.0-957.el7.x86_64.gz -rw------- 1 root root 3543471 Nov 9 2018 System.map-3.10.0-957.el7.x86_64 -rwxr-xr-x 1 root root 6639904 Jul 8 16:24 vmlinuz-0-rescue-9ccdf621e5984f3b8626614f6fa15a48 -rwxr-xr-x 1 root root 6639904 Nov 9 2018 vmlinuz-3.10.0-957.el7.x86_64 [root@node101.yinzhengjie.org.cn ~/backup]#
[root@node101.yinzhengjie.org.cn ~]# vim shell/server_alarm.sh #判断某个服务是否启动 [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# cat shell/server_alarm.sh #!/bin/bash # #******************************************************************** #Author: yinzhengjie #QQ: 1053419035 #Date: 2019-11-23 #FileName: shell/server_alarm.sh #URL: http://www.cnblogs.com/yinzhengjie #Description: The test script #Copyright notice: original works, no reprint! Otherwise, legal liability will be investigated. #******************************************************************** Host=127.0.0.1 res=`rpm -qa | grep nmap | head -1` if [ -z $res ] then yum -y install nmap &> /dev/null else echo “准备开始扫描主机服务!” fi ServiceStatus=$(nmap -sT $Host |grep tcp | grep http|awk '{print $2}') #使用nmap可以准确的判断一台服务器的服务是否正常。 if [ "$ServiceStatus" == "open" ] then echo "$(date) httpd is ok !" >> /tmp/HttpdAlarm-acc.log else systemctl restart httpd &>/dev/null #注意,如果不是你本机的话,不能直接这么干哟,需要先远程上去再执行命令! echo "`date` restart httpd!!" >> /tmp/HttpdAlarm-err.log fi [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# ss -ntl State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 128 *:22 *:* LISTEN 0 128 :::22 :::* [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# bash shell/server_alarm.sh “准备开始扫描主机服务!” [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# ss -ntl State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 128 *:80 *:* LISTEN 0 128 *:22 *:* LISTEN 0 128 :::22 :::* [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# cat /tmp/HttpdAlarm-err.log Sat Nov 23 07:40:44 CST 2019 restart httpd!! [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# bash shell/server_alarm.sh “准备开始扫描主机服务!” [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# cat /tmp/HttpdAlarm-acc.log Sat Nov 23 07:41:26 CST 2019 httpd is ok ! [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# vim shell/ip_judge.sh #判断IP是否合法 [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# cat shell/ip_judge.sh #!/bin/bash # #******************************************************************** #Author: yinzhengjie #QQ: 1053419035 #Date: 2019-11-23 #FileName: shell/ip_judge.sh #URL: http://www.cnblogs.com/yinzhengjie #Description: The test script #Copyright notice: original works, no reprint! Otherwise, legal liability will be investigated. #******************************************************************** read -p "Please input a ip address >>>: " IP if [[ "$IP" =~ ^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$ ]] then echo "$IP is legal" else echo "$IP is illegal" [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# bash shell/ip_judge.sh Please input a ip address >>>: 127.0.0.1 shell/ip_judge.sh: line 20: syntax error: unexpected end of file [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# vim shell/ip_judge.sh [root@node101.yinzhengjie.org.cn ~]# cat shell/ip_judge.sh #!/bin/bash # #******************************************************************** #Author: yinzhengjie #QQ: 1053419035 #Date: 2019-11-23 #FileName: shell/ip_judge.sh #URL: http://www.cnblogs.com/yinzhengjie #Description: The test script #Copyright notice: original works, no reprint! Otherwise, legal liability will be investigated. #******************************************************************** read -p "Please input a ip address >>>: " IP if [[ "$IP" =~ ^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$ ]] then echo "$IP is legal" else echo "$IP is illegal" fi [root@node101.yinzhengjie.org.cn ~]# bash shell/ip_judge.sh Please input a ip address >>>: 127.0.0.1 127.0.0.1 is legal [root@node101.yinzhengjie.org.cn ~]# bash shell/ip_judge.sh Please input a ip address >>>: 172.30.1.101 172.30.1.101 is legal [root@node101.yinzhengjie.org.cn ~]# bash shell/ip_judge.sh Please input a ip address >>>: 192.168.100.1 192.168.100.1 is legal [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# bash shell/ip_judge.sh Please input a ip address >>>: 256.256.256.256 256.256.256.256 is illegal [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# bash shell/ip_judge.sh Please input a ip address >>>: 255.255.255.255 255.255.255.255 is legal [root@node101.yinzhengjie.org.cn ~]# bash shell/ip_judge.sh Please input a ip address >>>: 11111 11111 is illegal [root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# vim shell/createuser.sh #编写创建脚本的案例 [root@node101.yinzhengjie.org.cn ~]# cat shell/createuser.sh #!/bin/bash # #******************************************************************** #Author: yinzhengjie #QQ: 1053419035 #Date: 2019-11-23 #FileName: shell/createuser.sh #URL: http://www.cnblogs.com/yinzhengjie #Description: The test script #Copyright notice: original works, no reprint! Otherwise, legal liability will be investigated. #******************************************************************** if [ -z "$1" ];then read -p "Please input a username >>>: " USER if [ -z "$USER" ];then echo "INPUT FLASE" exit 100 else USERNAME=$USER fi else USERNAME=$1 fi if id $USERNAME &> /dev/null;then echo "$USERNAME is exist" exit 20 else useradd $USERNAME && echo "$USERNAME is created" echo "yinzhengjie" | passwd --stdin $USERNAME &> /dev/null && echo "$USERNAME defalut password: yinzhengjie" passwd -e $USERNAME echo userinfo: `id $USERNAME` fi [root@node101.yinzhengjie.org.cn ~]# bash -n shell/createuser.sh [root@node101.yinzhengjie.org.cn ~]# bash shell/createuser.sh Please input a username >>>: root root is exist [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# bash shell/createuser.sh Please input a username >>>: yinzhengjie yinzhengjie is exist [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# bash shell/createuser.sh Please input a username >>>: jason jason is created jason defalut password: yinzhengjie Expiring password for user jason. passwd: Success userinfo: uid=1002(jason) gid=1002(jason) groups=1002(jason) [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# id jason uid=1002(jason) gid=1002(jason) groups=1002(jason) [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]#
3>.多分支if语句
if [ 条件判断式1 ] then 当条件判断式1成立时,执行的程序1 elif [ 条件判断式2 ] then 当条件判断式2成立时,执行程序2 else 当所有条件都不成立时,最后执行此程序 fi 温馨提示: 逐条件进行判断,第一次遇为“真”条件时,执行其分支,而后结束整个if语句
[root@node101.yinzhengjie.org.cn ~]# cat shell/judge_filetype.sh #判断用户输入的文件类型 #!/bin/bash # #******************************************************************** #Author: yinzhengjie #QQ: 1053419035 #Date: 2019-11-23 #FileName: shell/judge_filetype.sh #URL: http://www.cnblogs.com/yinzhengjie #Description: The test script #Copyright notice: original works, no reprint! Otherwise, legal liability will be investigated. #******************************************************************** read -p "Please input a filename:" file if [ -z "$file" ] then echo "Eorr,please input a filename!" exit 100 elif [ ! -e "$file" ] then echo "Your input is not a file!" elif [ -f "$file" ] then echo "$file is a regulare file!" elif [ -d "$file" ] then echo "$file is direcory!" else echo "$file is an other file!" fi [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# bash shell/judge_filetype.sh Please input a filename:/etc/passwd /etc/passwd is a regulare file! [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# bash shell/judge_filetype.sh Please input a filename:/root /root is direcory! [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# bash shell/judge_filetype.sh Please input a filename:/root2 Your input is not a file! [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# vim shell/song_of_five_rings.sh #五环之歌小脚本 [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# cat shell/song_of_five_rings.sh #!/bin/bash # #******************************************************************** #Author: yinzhengjie #QQ: 1053419035 #Date: 2019-11-23 #FileName: shell/song_of_five_rings.sh #URL: http://www.cnblogs.com/yinzhengjie #Description: The test script #Copyright notice: original works, no reprint! Otherwise, legal liability will be investigated. #******************************************************************** read -p "Please input your site >>>: " NUM [[ ! "$NUM" =~ ^[1-9]+$ ]] && { echo "Please input a digit";exit 10;} if [ "$NUM" -gt 6 ];then echo "Input false,please a [1-6] interger" exit 20 elif [ "$NUM" -eq 6 ];then echo "more 1 circle than 5" elif [ "$NUM" -eq 5 ];then echo "song of five rings" elif [ "$NUM" -eq 4 ];then echo "less 1 circle than 5" elif [ "$NUM" -eq 3 ];then echo "less 2 circle than 5" elif [ "$NUM" -eq 2 ];then echo "less 3 circle than 5" else echo "二环是马路,一环是紫禁城!" fi [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# bash shell/song_of_five_rings.sh Please input your site >>>: 11 Input false,please a [1-6] interger [root@node101.yinzhengjie.org.cn ~]# bash shell/song_of_five_rings.sh Please input your site >>>: 7 Input false,please a [1-6] interger [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# bash shell/song_of_five_rings.sh Please input your site >>>: 1 二环是马路,一环是紫禁城! [root@node101.yinzhengjie.org.cn ~]# bash shell/song_of_five_rings.sh Please input your site >>>: 2 less 3 circle than 5 [root@node101.yinzhengjie.org.cn ~]# bash shell/song_of_five_rings.sh Please input your site >>>: 3 less 2 circle than 5 [root@node101.yinzhengjie.org.cn ~]# bash shell/song_of_five_rings.sh Please input your site >>>: 4 less 1 circle than 5 [root@node101.yinzhengjie.org.cn ~]# bash shell/song_of_five_rings.sh Please input your site >>>: 5 song of five rings [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# vim shell/yes_or_no.sh #判断用户输入yes或no [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# cat shell/yes_or_no.sh #!/bin/bash # #******************************************************************** #Author: yinzhengjie #QQ: 1053419035 #Date: 2019-11-23 #FileName: shell/yes_or_no.sh #URL: http://www.cnblogs.com/yinzhengjie #Description: The test script #Copyright notice: original works, no reprint! Otherwise, legal liability will be investigated. #******************************************************************** read -p "Do you agree?(yes or no)" ANSWER #将用户输入的字母统一转换成小写 lower_answer=`echo $ANSWER | tr 'A-Z' 'a-z'` if [ $lower_answer = "yes" -o $lower_answer = "y" ];then echo YES elif [ $lower_answer = "no" -o $lower_answer = "n" ];then echo NO else echo "INPUT FALSE!" fi [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# bash shell/yes_or_no.sh Do you agree?(yes or no)y YES [root@node101.yinzhengjie.org.cn ~]# bash shell/yes_or_no.sh Do you agree?(yes or no)yes YES [root@node101.yinzhengjie.org.cn ~]# bash shell/yes_or_no.sh Do you agree?(yes or no)no NO [root@node101.yinzhengjie.org.cn ~]# bash shell/yes_or_no.sh Do you agree?(yes or no)n NO [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# bash shell/yes_or_no.sh Do you agree?(yes or no)yesno INPUT FALSE! [root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# vim shell/score.sh #根据分数来判断绩效 [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# cat shell/score.sh #!/bin/bash # #******************************************************************** #Author: yinzhengjie #QQ: 1053419035 #Date: 2019-11-25 #FileName: shell/score.sh #URL: http://www.cnblogs.com/yinzhengjie #Description: The test script #Copyright notice: original works, no reprint! Otherwise, legal liability will be investigated. #******************************************************************** read -p "Please input your score: " score if [[ ! "$score" =~ ^[0-9]+$ ]];then echo "Please input digit" exit 10 elif [ "$score" -gt 100 ];then echo "Your score is invalid!" exit 20 elif [ "$score" -lt 60 ];then echo "绩效为D,不及格" elif [ "$score" -lt 70 ];then echo "绩效为C,继续努力" elif [ "$score" -lt 80 ];then echo "绩效为B,超出任务预期" elif [ "$score" -lt 90 ];then echo "绩效为A,优秀员工" else echo "绩效为S,公司骨干人员" fi [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# bash shell/score.sh Please input your score: abc Please input digit [root@node101.yinzhengjie.org.cn ~]# bash shell/score.sh Please input your score: 999 Your score is invalid! [root@node101.yinzhengjie.org.cn ~]# bash shell/score.sh Please input your score: 1 绩效为D,不及格 [root@node101.yinzhengjie.org.cn ~]# bash shell/score.sh Please input your score: 60 绩效为C,继续努力 [root@node101.yinzhengjie.org.cn ~]# bash shell/score.sh Please input your score: 77 绩效为B,超出任务预期 [root@node101.yinzhengjie.org.cn ~]# bash shell/score.sh Please input your score: 82 绩效为A,优秀员工 [root@node101.yinzhengjie.org.cn ~]# bash shell/score.sh Please input your score: 97 绩效为S,公司骨干人员 [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]#
二.条件判断case语句
[root@node101.yinzhengjie.org.cn ~]# help case case: case WORD in [PATTERN [| PATTERN]...) COMMANDS ;;]... esac Execute commands based on pattern matching. Selectively execute COMMANDS based upon WORD matching PATTERN. The `|' is used to separate multiple patterns. Exit Status: Returns the status of the last command executed. [root@node101.yinzhengjie.org.cn ~]#
1>.语法格式
case $变量名 in "值1") 如果变量的值等于1,则执行程序1 ;; "值2") 如果变量的值等于2,则执行程序2 ;; "值3") 如果变量的值等于3,则执行程序3 ;; *) 如果变量的值都不是以上的值,则执行此程序 ;; esac 温馨提示: case语句和if...elif...else语句一样都是多分支条件语句,不过if多分支语句不同的是,case语句只能判断一种条件关系,而if语句可以判断多种条件关系。 case支持glob风格的通配符: *: 任意长度任意字符 ?: 任意单个字符 []:指定范围内的任意单个字符 a|b: a或b
2>.案例展示
[root@node101.yinzhengjie.org.cn ~]# vim shell/choose.sh #编写选择的地方并打印 [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# cat shell/choose.sh #!/bin/bash # #******************************************************************** #Author: yinzhengjie #QQ: 1053419035 #Date: 2019-11-23 #FileName: shell/choose.sh #URL: http://www.cnblogs.com/yinzhengjie #Description: The test script #Copyright notice: original works, no reprint! Otherwise, legal liability will be investigated. #******************************************************************** echo "If you want to beijing,please input [1]" echo "If you want to shanghai,please input [2]" echo "If you want to shijiazhuang,please input [3]" echo "If you want to wenzhou,please input [4]" read -t 30 -p "Where do you want to go ? >>> " choose case "$choose" in "1") echo "Go to beijing!" ;; "2") echo "Go to shanghai!" ;; "3") echo "Go to shijiazhuang!" ;; "4") echo "Go to wenzhou!" ;; *) echo "Please enter 1/2/3/4,Thanks!" ;; esac [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# bash shell/choose.sh If you want to beijing,please input [1] If you want to shanghai,please input [2] If you want to shijiazhuang,please input [3] If you want to wenzhou,please input [4] Where do you want to go ? >>> 1 Go to beijing! [root@node101.yinzhengjie.org.cn ~]# bash shell/choose.sh If you want to beijing,please input [1] If you want to shanghai,please input [2] If you want to shijiazhuang,please input [3] If you want to wenzhou,please input [4] Where do you want to go ? >>> 2 Go to shanghai! [root@node101.yinzhengjie.org.cn ~]# bash shell/choose.sh If you want to beijing,please input [1] If you want to shanghai,please input [2] If you want to shijiazhuang,please input [3] If you want to wenzhou,please input [4] Where do you want to go ? >>> 3 Go to shijiazhuang! [root@node101.yinzhengjie.org.cn ~]# bash shell/choose.sh If you want to beijing,please input [1] If you want to shanghai,please input [2] If you want to shijiazhuang,please input [3] If you want to wenzhou,please input [4] Where do you want to go ? >>> 4 Go to wenzhou! [root@node101.yinzhengjie.org.cn ~]# bash shell/choose.sh If you want to beijing,please input [1] If you want to shanghai,please input [2] If you want to shijiazhuang,please input [3] If you want to wenzhou,please input [4] Where do you want to go ? >>> 5 Please enter 1/2/3/4,Thanks! [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# vim shell/yes_or_no.sh #case版本判断用户输入的是yes还是no [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# cat shell/yes_or_no.sh #!/bin/bash # #******************************************************************** #Author: yinzhengjie #QQ: 1053419035 #Date: 2019-11-23 #FileName: shell/yes_or_no.sh #URL: http://www.cnblogs.com/yinzhengjie #Description: The test script #Copyright notice: original works, no reprint! Otherwise, legal liability will be investigated. #******************************************************************** read -p "Do you agree?(yes or no)" ANSWER case $ANSWER in [Yy][Ee][Ss]|[Yy]) echo "YES" ;; [Nn][Oo]|[Nn]) echo "NO" ;; *) echo "NOT YES OR NO" esac [root@node101.yinzhengjie.org.cn ~]# bash shell/yes_or_no.sh Do you agree?(yes or no)y YES [root@node101.yinzhengjie.org.cn ~]# bash shell/yes_or_no.sh Do you agree?(yes or no)yess NOT YES OR NO [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# bash shell/yes_or_no.sh Do you agree?(yes or no)yes YES [root@node101.yinzhengjie.org.cn ~]# bash shell/yes_or_no.sh Do you agree?(yes or no)no NO [root@node101.yinzhengjie.org.cn ~]# bash shell/yes_or_no.sh Do you agree?(yes or no)Y YES [root@node101.yinzhengjie.org.cn ~]# bash shell/yes_or_no.sh Do you agree?(yes or no)Yes YES [root@node101.yinzhengjie.org.cn ~]# bash shell/yes_or_no.sh Do you agree?(yes or no)No NO [root@node101.yinzhengjie.org.cn ~]# bash shell/yes_or_no.sh Do you agree?(yes or no)ye NOT YES OR NO [root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# vim shell/menu.sh #编写菜单选择案例 [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# cat shell/menu.sh #!/bin/bash # #******************************************************************** #Author: yinzhengjie #QQ: 1053419035 #Date: 2019-11-23 #FileName: shell/menu.sh #URL: http://www.cnblogs.com/yinzhengjie #Description: The test script #Copyright notice: original works, no reprint! Otherwise, legal liability will be investigated. #******************************************************************** cat <<EOF 1 鲍鱼 2 海参 3 佛跳墙 4 龙虾 5 帝王蟹 6 燕窝 EOF read -p "Choose the menu(1-6): " MENU case $MENU in 1|2) echo "The price 100" ;; 3|5) echo "The price 150" ;; 4|6) echo "The price 80" ;; *) echo "Choose false" ;; esac [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# bash -n shell/menu.sh #对脚本进行语法检查 [root@node101.yinzhengjie.org.cn ~]# bash shell/menu.sh #执行脚本 1 鲍鱼 2 海参 3 佛跳墙 4 龙虾 5 帝王蟹 6 燕窝 Choose the menu(1-6): 1 The price 100 [root@node101.yinzhengjie.org.cn ~]# bash shell/menu.sh 1 鲍鱼 2 海参 3 佛跳墙 4 龙虾 5 帝王蟹 6 燕窝 Choose the menu(1-6): 2 The price 100 [root@node101.yinzhengjie.org.cn ~]# bash shell/menu.sh 1 鲍鱼 2 海参 3 佛跳墙 4 龙虾 5 帝王蟹 6 燕窝 Choose the menu(1-6): 3 The price 150 [root@node101.yinzhengjie.org.cn ~]# bash shell/menu.sh 1 鲍鱼 2 海参 3 佛跳墙 4 龙虾 5 帝王蟹 6 燕窝 Choose the menu(1-6): 5 The price 150 [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# bash shell/menu.sh 1 鲍鱼 2 海参 3 佛跳墙 4 龙虾 5 帝王蟹 6 燕窝 Choose the menu(1-6): 7 Choose false [root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# vim shell/ops_menu.sh #模拟将工作中的任务半自动化,从而提升工作效率。 [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# cat shell/ops_menu.sh #!/bin/bash # #******************************************************************** #Author: yinzhengjie #QQ: 1053419035 #Date: 2019-11-23 #FileName: shell/ops_menu.sh #URL: http://www.cnblogs.com/yinzhengjie #Description: The test script #Copyright notice: original works, no reprint! Otherwise, legal liability will be investigated. #******************************************************************** cat <<EOF ipaddr yes_or_no backup EOF read -p "Please choose the menu[1-3]: " MENU case $MENU in 1) /root/shell/ip_judge.sh ;; 2) /root/shell/yes_or_no.sh ;; 3) /root/shell/file_backup.sh ;; *) echo "你的输入不合法!" exit 100 ;; esac [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# bash shell/ops_menu.sh ipaddr yes_or_no backup Please choose the menu[1-3]: 1 Please input a ip address >>>: 127.0.0.1 127.0.0.1 is legal [root@node101.yinzhengjie.org.cn ~]# bash shell/ops_menu.sh ipaddr yes_or_no backup Please choose the menu[1-3]: 2 Do you agree?(yes or no)Y YES [root@node101.yinzhengjie.org.cn ~]# bash shell/ops_menu.sh ipaddr yes_or_no backup Please choose the menu[1-3]: 3 [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# ll total 8 drwxr-xr-x 2 root root 36 Nov 23 09:06 backup drwxr-xr-x 2 root root 4096 Nov 23 09:06 shell [root@node101.yinzhengjie.org.cn ~]# [root@node101.yinzhengjie.org.cn ~]# ll backup/ total 106008 -rw-r--r-- 1 root root 108548748 Nov 23 09:06 boot_2019-11-23.tar.gz [root@node101.yinzhengjie.org.cn ~]#
当你的才华还撑不起你的野心的时候,你就应该静下心来学习。当你的能力还驾驭不了你的目标的时候,你就应该沉下心来历练。问问自己,想要怎样的人生。
欢迎交流学习技术交流,个人微信: "JasonYin2020"(添加时请备注来源及意图备注)
作者: 尹正杰, 博客: https://www.cnblogs.com/yinzhengjie/p/7675196.html