6.4bash條件測試

bash條件測試之文件測試:linux

          -a FILE  文件存在
          -e FILE: 文件存在則爲真;不然則爲假;shell

          -f FILE: 文件存在而且爲普通文件,則爲真;不然爲假;
          -d FILE: 文件存在而且爲目錄文件,則爲真;不然爲假;
          -L/-h FILE: 文件存在而且爲符號連接文件,則爲真;不然爲假;
          -b: 塊設備
          -c: 字符設備
          -S: 套接字文件
          -p: 命名管道編程

          -s FILE: 文件存在而且爲非空文件則爲真,不然爲假;vim

          -r FILE
          -w FILE
          -x FILEcentos

          file1 -nt file2: file1的mtime新於file2則爲真,不然爲假;
          file1 -ot file2:file1的mtime舊於file2則爲真,不然爲假;bash

    例如:若是wget命令對應的可執行文件存在且可執行,則使用它下載http://172.16.0.1/centos6.5.repo至當前目錄中;測試

        #!/bin/bash
        #
        downURL='http://172.16.0.1/centos6.5.repo'
        downloader=`which wget`ui

        if [ -x $downloader ]; then
            $downloader $downURL
        fi
注意:
-----------------------------------------------------------------
這裏是須要注意文件判斷的順序的,要 先 判斷是鏈接文件在判斷是 普通文件
-----------------------------------------------------------------
    練習:給定一個文件路徑 
        一、判斷此文件是否存在;不存在,則說明文件不存,並直接結束腳本;
        二、若是文件是否普通文件,則顯示爲「regular file」;
           若是文件是目錄,則顯示爲「directory」;
           若是文件是連接文件,則顯示爲「Symbolic file";
           不然,則顯示爲「unknown type.」rest

            #!/bin/bash
            #
            if [ ! -e $1 ]; then
                echo "file not exist."
                exit 8
            fiip

            if [ -L $1 ]; then
                echo "Symbolic file"
            elif [ -d $1 ]; then
                echo "Directory"
            elif [ -f $1 ]; then
                echo "regular file."
            else
                echo "unknown."
            fi

    練習:寫一個腳本,完成以下任務:
        一、分別複製/var/log下的文件至/tmp/logs/目錄中;
        二、複製目錄時,才使用cp -r
        三、複製文件時,使用cp
        四、複製連接文件,使用cp -d
        五、餘下的類型,使用cp -a
注意:
1.比較/var/log下的文件時,不能 -d|-f|-L $filename這樣比較,還有目錄頭呢,切記不要忘了/var/log
應該   /var/log/$filename    在比較別的目錄時,必定不能忘記目錄頭,不然必定會出錯
-----------------------------------------------------
[root@linux_basic scripts]#cat filecopy.sh
#!/bin/bash
#
srcdir="/var/log"
#if [ ! -d /var/logs ];then
#if [ ! -e /var/logs ];then
if [ ! -e /tmp/logs ];then
   mkdir -p /tmp/logs
#   destdir="/tmp/logs/"
   destdir="/tmp/logs"
fi

for file in $(ls $srcdir);do
   if [ -d $srcdir/$file ];then
      cp -r $srcdir/$file $destdir
   elif [ -L $srcdir/$file ];then
      cp -d $srcdir/$file $destdir
   elif [ -f $srcdir/$file ];then
      cp $srcdir/$file $destdir
   else
      cp -a $srcdir/$file $destdir
   fi
done  
------------------------------------------------------


    寫一個腳本,完成以下任務,其使用形式以下所示:
        script.sh {start|stop|restart|status}
    其中:
        若是參數爲空,則顯示幫助信息,並退出腳本;
        若是參數爲start,則建立空文件/var/lock/subsys/script,並顯示「starting script successfully.」
        若是參數爲stop,則刪除文件/var/lock/subsys/script,並顯示「Stop script successfully.」
        若是參數爲restart,則刪除文件/var/locksubsys/script並從新建立,然後顯示「Restarting script successfully.」
        若是參數爲status,那麼:
            若是文件/var/lock/subsys/script存在,則顯示「Script is running...」,不然,則顯示「Script is stopped.」

        說明:script.sh是腳本文件名,在建立時,其名稱能夠本身隨意定義,但若是其名稱發生變化,在/var/lock/sussys/下的文件名也要隨之而變;
-----------------------------------------------------------
[root@linux_basic scripts]#cat service.sh
#!/bin/bash
#
if [ -z "$1" ];then
   echo "Usage:$(basename $0) {start|stop|restart|status}"
   exit 1
elif [ "$1" == "start" ];then
   touch /var/lock/subsys/$(basename $0)
   echo "starting $(basename $0) successful."
elif [ "$1" == "stop" ];then
   rm -f /var/lock/subsys/$(basename $0)
   echo "stop $(basename $0) successful"
elif [ "$1" == "restart" ];then
   rm -f /var/lock/subsys/$(basename $0)
   touch /var/lock/subsys/$(basename $0)
   echo "Rstarting $(basename $0) successful"
elif [ "$1" == "status" ];then
   if [ -e /var/lock/subsys/$(basename $0) ];then
      echo "$(basename $0) is runing..."
   else
      echo "$(basename $0) is stopped"
   fi
fi
[root@linux_basic scripts]#bash -n service.sh
[root@linux_basic scripts]#chmod +x service.sh
[root@linux_basic scripts]#bash -x ./service.sh
+ '[' -z '' ']'
++ basename ./service.sh
+ echo 'Usage:service.sh {start|stop|restart|status}'
Usage:service.sh {start|stop|restart|status}
+ exit 1
[root@linux_basic scripts]#bash -x ./service.sh start
+ '[' -z start ']'
+ '[' start == start ']'
++ basename ./service.sh
+ touch /var/lock/subsys/service.sh
++ basename ./service.sh
+ echo 'starting service.sh successful.'
starting service.sh successful.
[root@linux_basic scripts]#bash -x ./service.sh stop
+ '[' -z stop ']'
+ '[' stop == start ']'
+ '[' stop == stop ']'
++ basename ./service.sh
+ rm -f /var/lock/subsys/service.sh
++ basename ./service.sh
+ echo 'stop service.sh successful'
stop service.sh successful
[root@linux_basic scripts]#bash -x ./service.sh restart
+ '[' -z restart ']'
+ '[' restart == start ']'
+ '[' restart == stop ']'
+ '[' restart == restart ']'
++ basename ./service.sh
+ rm -f /var/lock/subsys/service.sh
++ basename ./service.sh
+ touch /var/lock/subsys/service.sh
++ basename ./service.sh
+ echo 'Rstarting service.sh successful'
Rstarting service.sh successful
[root@linux_basic scripts]#bash -x ./service.sh status
+ '[' -z status ']'
+ '[' status == start ']'
+ '[' status == stop ']'
+ '[' status == restart ']'
+ '[' status == status ']'
++ basename ./service.sh
+ '[' -e /var/lock/subsys/service.sh ']'
++ basename ./service.sh
+ echo 'service.sh is runing...'
service.sh is runing...
----------------------------------------------------------------       
       
   
        bash編程之交互編程   隨着用戶的輸入而改變

    read
        -p "prompt"  顯示prompt後等待輸入
        -t timeout   等待t秒後不輸入則退出
[root@linux_basic scripts]#read a
hello
[root@linux_basic scripts]#echo $a
hello
[root@linux_basic scripts]#read a b
hello
[root@linux_basic scripts]#echo $a
hello
[root@linux_basic scripts]#echo $b

[root@linux_basic scripts]#read a b c
12 25 69 30
[root@linux_basic scripts]#echo $a
12
[root@linux_basic scripts]#echo $b
25
[root@linux_basic scripts]#echo $c
69 30

    例如:輸入用戶名,可返回其shell
        #!/bin/bash
        #
        read -p "Plz input a username: " userName

        if id $userName &> /dev/null; then
            echo "The shell of $userName is `grep "^$userName\>" /etc/passwd | cut -d: -f7`."
        else
            echo "No such user. stupid."
        fi

    例子:顯示一個以下菜單給用戶:
        cpu) show cpu infomation
        mem) show memory infomation
        *) quit

        一、若是用戶選擇了cpu,則顯示/proc/cpuinfo文件的內容;
        二、若是用戶選擇了mem,則顯示/proc/meminfo文件的內容;
        三、退出

            #!/bin/bash
            #
            echo "---------menu----------"
            echo "cpu) show cpu infomation"
            echo "mem) show memory infomation"
            echo "*) quit"
            echo "-------menu------------"

            read -p "Plz give your choice: " choice

            if [ "$choice" == 'cpu' ]; then
                cat /proc/cpuinfo
            elif [ "$choice" == 'mem' ]; then
                cat /proc/meminfo
            else
                echo "Quit"
                exit 3
            fi

 

            #!/bin/bash
            #
            cat << EOF
            -------menu------------
            cpu) show cpu infomation
            mem) show memory infomation
            *) quit
            -------menu------------
            EOF

            read -p "Plz give your choice: " choice

            if [ "$choice" == 'cpu' ]; then
                cat /proc/cpuinfo
            elif [ "$choice" == 'mem' ]; then
                cat /proc/meminfo
            else
                echo "Quit"
                exit 3
            fi


字串測試中的模式匹配
    [[ "$var" =~ PATTERN ]]  判斷$var是否和 PATTERN模式相同
 
    例如:讓用戶給定一個用戶名,判斷其是否擁有可登陸shell;
        /bin/sh, /bin/bash, /bin/zsh, /bin/tcsh, /sbin/nologin, /sbin/shutdown


        #!/bin/bash
        #
        read -p "Plz input a username: " userName
        userInfo=`grep "^$userName\>" /etc/passwd`

        if [[ "$userInfo" =~ /bin/.*sh$ ]]; then
            echo "can login"
        else
            echo "cannot login"
        fi

    練習:寫一個腳本,完成以下功能
        使用格式:
            script.sh  /path/to/somefile

vim + FILENAME 打開文件,而且處於文件最後一行行首
        一、可接受一個文件路徑參數:
            若是此文件不存在,則建立之,則自動爲其生成前n行相似以下:
                #!/bin/bash
                # description:
                # version:
                # date:
                # author: mageedu
                # license: GPL
            然後使用vim打開此文件,並讓光標處在最後一行的行首
            若是文件存在、且是bash腳本,則使用vim打開之,光標自動處行最後一行的行首;
            不然,退出;
---------------------------------------------------------------
[root@linux_basic scripts]#cat createfile.sh
#!/bin/bash
#
if [ -z $1 ];then
   echo "Usage:$(basename $0) FILENAME"
   exit 1
fi

if [ ! -e "$1" ];then
   touch $1
   cat > $1 << EOF
#!/bin/bash
# description:
# version:
# date:
# author: magedu
# license: GPL
EOF
   vim + $1
#elif [ -e "$1" -a "$(file $1 | grep -o "shell script"&>/dev/null)" ];then
在這種狀況下"$(file $1 | grep -o "shell script"&>/dev/null)"是有問題的,由於咱們要的是執行狀態值,而不
是執行結果,執行結果也是爲空的
elif [ -e "$1" ] && $(file $1 | grep -o "shell script"&>/dev/null);then
   vim + $1
else
   echo "quit..."
   exit 1
fi
---------------------------------------------------------------------

            若是正常編輯保存,
                判斷,若是文件沒有執行權限,則添加之;

                判斷,其是否有語法錯誤,若是有,提示;

相關文章
相關標籤/搜索