自动删除文件脚本(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的编辑器

相关文章
相关标签/搜索