shell腳本常用命令

1.在sh腳本中獲得系統當前時間作爲變量的值

#日期

date=$(date +%F)
#時間
timer=$(date +%T)
#納秒

ns=$(date +%N)

在shell中,沒有可以直接獲得毫秒的命令,通過下面的方法獲得系統當前的毫秒

#毫秒
ms=${ns:0:3}

2.判斷文件是否存在,判斷路徑是否存在以及是否具有可執行權限

filePath=/home/monitor/test/
#判斷路徑是否存在以及具有可執行權限,如果沒有則創建
if [ ! -x ${filePath} ]
then
mkdir ${filePath}
fi

fileName=${date}${timer}${ns}.temp
tempfile=${filePath}${fileName}
#這裏的-f參數判斷文件是否存在,如果存在則刪除再創建一個新的空的文件
if [ -f ${tempfile} ] 
then
rm ${tempfile}
touch ${tempfile}
fi

3.sh中分割輸入的字符串

例如:test.sh文件中的內容如下:
#split parameter by "++",part one is command,part 2 is interval time,part 3 is fileName include absolute path
command=`echo ${@}|awk -F '++' '{print $1}'`
interval=`echo ${@}|awk -F '++' '{print $2}'`
fileName=`echo ${@}|awk -F '++' '{print $3}'`

執行test.sh文件:./test.sh a++b++c
那麼command=a;interval=b;fileName=c

4.sh中無限循環執行一段代碼

#1 -eq 1的值爲true
while [ 1 -eq 1 ]
do
echo "do something"
        sleep 5
done

上面的代碼每隔5秒執行echo語句

5.sh中的邏輯運算與或非(and、or、!)

在一個[]中括號中:
與:-a
或:-o

多個[]之間使用:
與:&&
或:||

#下面的if語句判斷:如果三個參數都不爲空
if [ ${command} -a ${interval} -a ${fileName} ]; then
while [ 1 -eq 1 ]
do
#日期
date=$(date +%F)
#時間
timer=$(date +%T)
#納秒
ns=$(date +%N)
#毫秒
ms=${ns:0:3}
beginStr="*******start:${date} ${timer}.${ms}"
echo ${beginStr} >> ${fileName}
${command} >> ${fileName}
echo ${endStr} >> ${fileName}
echo "producering "${command}" to "${fileName}",interval time is "${interval}
        sleep ${interval}
done
else
echo "please input the parameters!!!"
fi

在測試時注意腳本中的空格,特別在條件判斷中的空格,它們都是必須的
發佈了42 篇原創文章 · 獲贊 6 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章