Shell本身是一種用C語言編寫的程序,從用戶的角度來看,Shell是用戶與Linux操作系統溝通的橋梁。用戶既可以輸入命令執行,又可以利用 Shell腳本編程,完成更加復雜的操作。
首行中的符號#!告訴系統其后路徑所指定的程序即是解釋此腳本文件的Shell程 序。如果首行沒有這句話,在執行腳本文件的時候,將會出現錯誤。后續的部分就是主程序,Shell腳本像高級語言一樣,也有變量賦值,也有控制語句。除第 一行外,以#開頭的行就是注釋行,直到此行的結束。如果一行未完成,可以在行尾加上",這個符號表明下一行與此行會合並為同一行
#將所需目錄中選中的日期內文件夾打包(tar包) 並按輸入時間間隔分段 #1 所需目錄 #2 起始日期 #3 截止日期 #4 ---時間間隔(月份) #5 ---輸出目錄 #!/bin/bash input_dir=$1 #第一個參數 date_start=$2 #第二個參數 date_end=$3 #結束日期格式轉換 end=$(date +%s -d "${date_end}") start=$(date +%s -d "${date_start}") #input split interval m=3 #時間間隔參數 3:表示每3個月一個壓縮包 output_dir="/calogs/test/test2" echo "===START===" cd $input_dir value=$(($end-$start)) #時間相隔天數 #刪除操作 while test $value -gt 0 do mthago=$(date +%Y%m%d -d "${date_start} ${m} months") mthago=$(date +%Y%m%d -d "${mthago} 1 days ago") #轉換為日期格式 mthago_time=$(date +%s -d "${mthago}") #比較三月后日期是否大於結束日期 comp1=$(($end-$mthago_time)) if test $comp1 -le 0 then mthago=$date_end #如果小於則賦值為結束日期 mthago_time=$(date +%s -d "${mthago}") fi outdir=$output_dir/${input_dir##*/}-$date_start-$mthago.tar #tar包名稱 # echo $outdir if test -f $outdir then rm -f $outdir fi date_start=$(date +%Y%m%d -d "${mthago} 1 days ") #獲取開始某日期后一天 1為變量(整數) start=$(date +%s -d "${date_start}") value=$(($end-$start)) done #添加操作 date_start=$2 start=$(date +%s -d "${date_start}") value=$(($end-$start)) while test $value -ge 0 do mthago=$(date +%Y%m%d -d "${date_start} ${m} months") #獲取開始某日期幾個月后一天 ${m}為變量(整數) mthago=$(date +%Y%m%d -d "${mthago} 1 days ago") #轉換為日期格式 mthago_time=$(date +%s -d "${mthago}") #比較三月后日期是否大於結束日期 comp1=$(($end-$mthago_time)) if test $comp1 -le 0 #$comp1是否小於0 then mthago=$date_end #如果小於則賦值為結束日期 mthago_time=$(date +%s -d "${mthago}") fi outdir=$output_dir/${input_dir##*/}-$date_start-$mthago.tar comp2=$(($mthago_time-$start)) while test $comp2 -ge 0 #$comp2是否大於等於0 do if test -d $date_start then tar -cf $outdir $date_start #初次生成tar包 echo "$outdir" date_start=$(date +%Y%m%d -d "${date_start} 1 days ") start=$(date +%s -d "${date_start}") comp2=$(($mthago_time-$start)) while test $comp2 -ge 0 do if test -d $date_start #判斷文件夾是否存在 then tar -uf $outdir $date_start #往tar包中追加文件 #echo "[ $date_start ]" fi date_start=$(date +%Y%m%d -d "${date_start} 1 days ") start=$(date +%s -d "${date_start}") comp2=$(($mthago_time-$start)) done else date_start=$(date +%Y%m%d -d "${date_start} 1 days ") start=$(date +%s -d "${date_start}") comp2=$(($mthago_time-$start)) fi done value=$(($end-$start)) done echo "===FINISHED==="
運行命令(sh文件后跟參數):
sh /calogs/new.sh /calogs/test 20160101 20161230
