自動刪除文件的腳本


 

每天在/home/face/capturepic/2017/目錄下都會產生很多文件
/home/face/capturepic/2017/4/21
/home/face/capturepic/2017/4/22
 
希望的是每天只保留當天的文件夾,其他的文件夾刪除
改寫的.sh腳本如下

 

!/bin/bash
dir="/home/face/capturepic/2017/"
Available=`df -k | sed -n '/sda3/p' | awk '{print int($5)}'`
if [ $Available -gt 10 ];then
echo "available less 10 "
for mou in `ls $dir`
 do
 tmou=date +%m
 if [ $mou -lt $tmou ];then
echo "delete dir $dir$mou "
rm -rf $dir$mou
 elif [ $mou -eq $tmou ];then
for day in `ls $dir$mou/`
 do
 today=date +%d
 if [ $day -ne $today ];then
echo "delete dir $dir$tmou/$day "
rm -rf $dir$tmou/$day
 fi
done
fi
done
fi

  

定時執行的corn文件如下(每分鍾執行一次)
 

 

* * * * * ./test.sh
* * * * * ./test. sh 最好寫一下腳本的絕對路徑,因為最后放到crontab里面,當前路徑就不同了
最好改為如下
* * * * * /home/test.sh
 
還有就是腳本里面用到的一些文件之類的,最好也用絕對路徑
crontab XXX.cron
直接加入定時腳本中
 
 
 
crontab -l
能夠查看腳本是否放在了crontab里面
 
如果運行了,可以運行如下命令查看最近日志,如果看不到日志,說明根本沒運行
root@u3-server:/home/u3/mjl# tail /var/log/cron.log
Oct 15 11:32:01 u3-server CRON[15159]: (root) CMD (/home/u3/mjl/watchdog.sh)
Oct 15 11:32:01 u3-server CRON[15158]: (CRON) info (No MTA installed, discarding output)
Oct 15 11:33:01 u3-server CRON[15293]: (root) CMD (/home/u3/mjl/watchdog.sh)
Oct 15 11:33:01 u3-server CRON[15292]: (CRON) info (No MTA installed, discarding output)
Oct 15 11:34:01 u3-server CRON[15427]: (root) CMD (/home/u3/mjl/watchdog.sh)
Oct 15 11:34:01 u3-server CRON[15426]: (CRON) info (No MTA installed, discarding output)
Oct 15 11:35:01 u3-server CRON[15561]: (root) CMD (/home/u3/mjl/watchdog.sh)
Oct 15 11:35:01 u3-server CRON[15560]: (CRON) info (No MTA installed, discarding output)
Oct 15 11:36:01 u3-server CRON[15695]: (root) CMD (/home/u3/mjl/watchdog.sh)
Oct 15 11:36:01 u3-server CRON[15694]: (CRON) info (No MTA installed, discarding output)

  

有時候/var/log/cron.log 不一定有日志
需要在cron腳本里面加入重定向日志,如
* * * * * /home/jyzbyj/mjl/watchdog/watchdog.sh >> /home/jyzbyj/mjl/watchdog/mylog.log 2>&1
另外service cron start可以正常啟動服務
一些網上的資料說 /sbin/service crond start ,我在ubuntu下面不能執行
 
開機的時候自動啟動服務
u3@u3-server:~/mjl$ cat /etc/rc.local
#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
service cron start
exit 0

  

 
殺死所有名稱叫test的進程
kill.sh
killall test
運行在后台,並且設置為init進程的子進程,不隨終端的關閉退出
start.sh
cd /home/user/test/
setsid ./test &
 注意,不要放在/etc/ 等系統目錄下面,可能導致沒有執行權限
cron腳本在不同的用戶有不同的設置,所以執行程序一定要保證能夠在當前用戶能執行
 
以上文章轉載他人,時間比較久,所以沒有備注原創鏈接,望諒解!

 


免責聲明!

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



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