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 ~]#