shell腳本中case的用法


 shell腳本中case選擇語句可以結合read指令實現比較好的交互應答操作,case接收到read指令傳入的一個或多個參數,然后case根據參數做選擇操作。

 case的語法如下

 

case  $char  in
 
        C | c )
                command 1
                ;;          #每一個選擇都以雙 ;; 結束
        M | m )
                command 2
                ;;
            *   )               #  * 未匹配到相符的其他值                                                                                                                                                                 
                echo  “error”
               ;;

esac           #case的結束語句是以esac 結束

 

下面結合一個簡單的小功能使用,腳本中同時也用到了函數的方法;簡單查看系統信息

 

#!/bin/bash
echo "check system run status"
echo "show CPUinfo: C/c "
echo "show Memery used: M/m "
echo "show Disk use status: D/n "
echo "show System user login: U/n "
echo "show System load average:L/l"
echo "show System Ip address: I/i"

read_input () {
read  -t 10 -p "please Input C/M/D/U/L/I : " char
}

show_status () {

case $char in 
        
        C | c )
                cat /proc/cpuinfo | grep -o -i 'model name.*'
                ;;
        M | m )
                free -m
                ;;
        D | d )
                df -h
                ;;
        U | u )
                w
                ;;
        L | l )
                top | head -1 | cut -d " " -f 11-15
                ;;
        I | i )
                ifconfig | grep -o "[0-9.]\{7,\}" | head -1
                ;;
        * )
                echo "The characters you have entered are wrong. Please look at the hints"
                ;;
esac
}


for i in $( seq 1 10)
do
read_input
show_status
if [ $i -eq 10 ]; then
        echo "已經到達查詢的最大次數,腳本退出;"
fi
done

看看測試結果

[root@yufu home]# ./test.sh 
check system run status
show CPUinfo: C/c 
show Memery used: M/m 
show Disk use status: D/n 
show System user login: U/n 
show System load average:L/l
show System Ip address: I/i
please Input C/M/D/U/L/I : The characters you have entered are wrong. Please look at the hints
please Input C/M/D/U/L/I : m
             total       used       free     shared    buffers     cached
Mem:          1869        165       1703          0         21         48
-/+ buffers/cache:         96       1773
Swap:         1999          0       1999
please Input C/M/D/U/L/I : c
model name    : Intel(R) Core(TM) i5-3317U CPU @ 1.70GHz
model name    : Intel(R) Core(TM) i5-3317U CPU @ 1.70GHz
please Input C/M/D/U/L/I :

 

 
        

這樣可以實現交互式地傳遞參數,並且通過循環可以設置選擇次數,通過read  -t 限制等待輸入時長等


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM