自動刪除文件腳本(Linux shell腳本)

天天在/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文件以下(每分鐘執行一次)

linux

* * * * * ./test.sh
* * * * * ./test.sh 最好寫一下腳本的絕對路徑,由於最後放到crontab裏面,當前路徑就不一樣了 
最好改成以下
* * * * * /home/test.sh

還有就是腳本里面用到的一些文件之類的,最好也用絕對路徑

crontab XXX.cron
 

直接加入定時腳本中ubuntu





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能夠正常啓動服務windows

一些網上的資料說 /sbin/service crond start ,我在ubuntu下面不能執行bash

 

開機的時候自動啓動服務less

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.shthis

killall test

運行在後臺,而且設置爲init進程的子進程,不隨終端的關閉退出spa

start.sh日誌

cd /home/user/test/
setsid ./test  &    

 注意,不要放在/etc/ 等系統目錄下面,可能致使沒有執行權限code

cron腳本在不一樣的用戶有不一樣的設置,因此執行程序必定要保證可以在當前用戶能執行

 

 

提示:若是你的腳本老是報錯,極可能是你用了windows下面的編輯器,最好有linux的編輯器

相關文章
相關標籤/搜索