Shell下變量比較


  •    字符串變量表達式
If  [ $a = $b ]                 如果string1等於string2
                                字符串允許使用賦值號做等號
if  [ $string1 !=  $string2 ]   如果string1不等於string2       
if  [ -n $string  ]             如果string 非空(非0),返回0(true)  
if  [ -z $string  ]             如果string 為空
if  [ $sting ]                  如果string 非空,返回0 (和-n類似)


兩個參數對比


[root@CentOS6 shell]# vi test.sh 
[root@CentOS6 shell]# cat test.sh 
#!/bin/bash
if [ $1 -ge $2 ];
 then echo -e "\033[41;37m <參數不對,第一個數字要小於第二個,退出此次操作!> \033[0m" 
else
 echo "起止時間依次是:`date -d "$2 days ago" +%Y%m%d`--`date -d "$1 days ago" +%Y%m%d`";
fi
[root@CentOS6 shell]# ./test.sh 1 2
起止時間依次是:20141116--20141117
[root@CentOS6 shell]# ./test.sh 2 1
 <參數不對,第一個數字要小於第二個,退出此次操作!> 
[root@CentOS6 shell]# ./test.sh 2 8
起止時間依次是:20141110--20141116
[root@CentOS6 shell]# ./test.sh 1 90
起止時間依次是:20140820--20141117
[root@CentOS6 shell]# ./test.sh 1 100
起止時間依次是:20140810--20141117
[root@CentOS6 shell]# ./test.sh 1 1
 <參數不對,第一個數字要小於第二個,退出此次操作!> 
[root@CentOS6 shell]#

cleanup.sh
#!/bin/bash
LOG_DIR=/var/log ROOT_UID=0 # 只有用戶ID變量$UID值為0的用戶才有root權限. LINES=50 # 默認的行數 E_XCD=66 # 不能進入到目錄時的退出代碼值 E_NOTROOT=67 # 不是root用戶時退出的代碼值 # 必須以root用戶運行,以下進行檢測 if [ "$UID" -ne "$ROOT_UID" ] then echo "Must be root to run this script." exit $E_NOTROOT fi if [ -n "$1" ] # 測試是否提供了命令行參數(即是測試命令行參數至少有一個參數) then lines=$1 else lines=$LINES # Default, if not specified on command line. fi # Stephane Chazelas建議, #+ 下面是一種更好的檢測命令行參數的方法, #+ 但是對於現在來說還是有些高級。 # # E_WRONGARGS=65 # 不是數字參數 (參數格式不對)時的退出碼 # # case "$1" in # "" ) lines=50;; # *[!0-9]*) echo "Usage: `basename $0` file-to-cleanup"; exit $E_WRONGARGS;; # * ) lines=$1;; # esac # #* 可以跳到"循環"那章閱讀開頭一部分去了解上面的代碼意思. cd $LOG_DIR if [ `pwd` != "$LOG_DIR" ] # 也可以用 if [ "$PWD" != "$LOG_DIR" ] # 如果工作目錄不在/var/log里? then echo "Can't change to $LOG_DIR." exit $E_XCD fi #在操作清空日志文件之前再次檢查是否在正確的目錄里 # 可以像下面再次確定是否在正確的目錄里: # # cd /var/log || { # echo "Cannot change to necessary directory." >&2 # exit $E_XCD; # } tail -$lines messages > mesg.temp # 保存message日志文件最后面幾行日志信息到臨時文件. mv mesg.temp messages # 然后用臨時文件覆蓋messages日志文件 # cat /dev/null > messages #* 上面這句把messages日志文件全部清空,這樣沒有上面那樣保留最后幾行安全 cat /dev/null > wtmp # ': > wtmp' and '> wtmp' have the same effect. echo "Logs cleaned up." exit 0


免責聲明!

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



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