shell學習之條件測試(參考shell指令碼編程訣竅)

來源:互聯網
上載者:User

標籤:shell 條件測試


1關於test測試,查看man文檔知

運算式的判斷

( EXPRESSION )                    #EXPRESSION is true

! EXPRESSION                      #EXPRESSION is false

EXPRESSION1 -a EXPRESSION2        #both are true,-o means or

 

字串是否為空白,相等

-n STRING  #the length of STRING is nonzero,-n can be removed

-z STRING  #the length of STRING is zero(nonexists,or null)

#when comes to string, we use =

STRING1 = STRING2       #the strings are equal

STRING1 != STRING2      #the strings are not equal


數位比較

#when comes to number,we use different eq ne and so on

INTEGER1 -eq INTEGER2   #INTEGER1 is equal to INTEGER2

-ge  greater or equal

-gt  greater than 

    -le   -lt   -ne   I

比較檔案是否為連結檔案     

FILE1 -ef FILE2         #FILE1 and FILE2 have the same device and inode numbers

eg

                [[email protected] shell]# test  txt  -ef txthardlink                             [[email protected] shell]# echo $?                0                [[email protected] shell]# test  txt  -ef txtlink(soft)                [[email protected] shell]# echo $?                0


所以這個是測試是否是檔案連結(包括軟硬),大家可以自己試試


比較檔案的修改時間

FILE1 -nt FILE2#FILE1 is newer/older (modification date) than FILE2,timestamp

FILE1 -ot FILE2    檔案有修改時間modify time (強調內容改變) 改變時間change time(本質即相關屬性改變)  接觸時間access time(被訪問)


檔案類型

-b FILE     #type:block special

-c FILE     #type:character special

-d FILE     # a directory

-e FILE     #FILE exists是否存在

-s FILE     #FILE exists and has a size greater than zero是否為空白

-f FILE     #a regular file

-u FILE     #set user-ID   SUID

-g FILE     #FILE exists and is set-group-ID使用時暫時擁有檔案所屬組的許可權SGID

-G FILE     #FILE exists and is owned by the effective group ID真的Group

-h FILE     #a symbolic link (same as -L)

-k FILE     #FILE exists and has its sticky bit set   sticky位其他使用者只能添加不能刪除

-L FILE     #FILE exists and is a symbolic link (same as -h)

-O FILE     #FILE exists and is owned by the effective user ID

-p FILE     #a named pipe

-S FILE     #FILE exists and is a socket

-r FILE     #FILE exists and read permission is granted

you can  use -w  ,write  ,-x  execute


-t FD       #file descriptor FD is opened on a terminal

很多,但有規律,常用的並不多


2 上面的測試還可用於類似[ -e $num ]結構中

3 if/then條件測試結構(還有case,while,等結構可能後面會涉及,不懂請自行baidu)

①if  [ condition ]

then

COMMAND

fi

or

if  [ condition ];then 

COMMAND

fi

②if  [ condition ];then 

COMMAND1

else

COMMAND2

fi

③if  [ condition ];then 

COMMAND1

elif  [ condition ];then 

COMMAND2

else

COMMAND3

fi


big eg.

#if1.sh#!/bin/bash#read -p "guss who am i?"  HELLOtest -z $HELLO&&echo "wrong argv please reinput!"&&exit 1if [ "$HELLO" = "Jack" ];thenecho "oh,you are jack!"elif [ "$HELLO" = "Kitty" ];thenecho "oh,you are Kitty!"elif [ "$HELLO" = "Mike" ];thenecho "oh,you are Mike!"elseecho "sorry i don‘t remember."echo "ok,my name is $HELLO"fi


通常if then可以改為[[ conditon ]]&&條件ok||條件不ok

3 [[ ]]與[]的區別

通常表現在以下幾個方面

[ ]使用-a,-o串連多個邏輯運算式,而[[ ]]使用&&,||串連多個運算式

[ ]:萬用字元不起作用,[[ ]]會展開萬用字元

[ ]不能使用比較子,如>,<,而[[ ]]可以

4 (())

測試數字運算式

結果為0返回1,結果為其他返回0

[[email protected] ~]# ((1-1))

[[email protected] ~]# echo $?

1

[[email protected] ~]# ((1+1))

[[email protected] ~]# echo $?

0

5 條件判斷與測試的小程式

#-N可以表示檔案是否被修改#所以有下面的一段監控檔案是否被修改的shell script#watchfile.sh#!/bin/bashTT=5 #5 secondsNFILE=$1 #the watched file#origin length of the filelen=`wc -l $NFILE |awk ‘{print $1 }‘`echo " $NFILE has  $len lines "while :do  if [ -N $NFILE ]  then  echo "`date`:new entry in $NFILE"  newlen=`wc -l $NFILE |awk ‘{print $1 }‘`  newlines=`expr $newlen - $len`  tail -$newlines $NFILE  len=$newlen  fi  sleep $TTdone


6 Regex的測試程式

#RE.sh#!/bin/bashfor deb in /root/shell/*dopkgname=`basename $deb`if [[ $pkgname =~ .*\.deb ]];then#提醒 if緊跟著的[有空格,$前面有一個空格,deb後面有個空格  echo "FILE $pkgname is a debian package"else  echo "File $pkgname is not a debian package"fidone

另一個添加捕獲的

#如何捕獲括弧中的字串#儲存在BASH_REMATCH[]數組中#RE1.sh#!/bin/bash# manage to know your nameread -p "please input your fullname:" NAMEif [[ $NAME =~  (.*)[[:space:]](.*) ]];thenecho "你姓 ${BASH_REMATCH[2]}"echo "你叫 ${BASH_REMATCH[1]}"echo "全稱 ${BASH_REMATCH[0]}"fi執行結果[[email protected] shell]# ./RE1.sh please input your fullname:liancao liu你姓 liu你叫 liancao全稱 liancao liu

 7 一個猜數位指令碼

#一個猜數位sh#numguess.sh#!/bin/bash#you may want to guess between 0-50WORDS=51GUESS=-1TIME=0BELOW=0TOP=`expr $WORDS - 1 `let ANSWER=($RANDOM % $WORDS)let ANSWER+=-1while [ "$GUESS" -ne "$ANSWER" ] doecho "the number is between $BELOW and $TOP"        read -p "your guess:" GUESSlet TIME+=1if [ "$GUESS" -lt "$ANSWER" ] ;then        echo "please input larger"BELOW=`expr $GUESS + 1`elif [ "$GUESS" -gt "$ANSWER" ];thenecho "please input smaller"TOP=`expr $GUESS - 1 `else        echo "right! you guessed $TIME times"        fidone


本文出自 “啟學的學習之路” 部落格,請務必保留此出處http://qixue.blog.51cto.com/7213178/1654508

shell學習之條件測試(參考shell指令碼編程訣竅)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.