---
title: "crontab 每月最后一天执行"
author: "java_2007"
date: "2011-09-26T14:48:21Z"
tags: []
categories: ["操作系统"]
slug: "crontab"
draft: false
lastmod: "2011-09-26T14:48:21Z"
id: 1180661
url: "https://java-2007.iteye.com/blog/1180661"
---

如何设定crontab在每月最后一天执行一种方法：

for Linux  
0 8 28-31 * * \[ \`date -d tomorrow +\\%e\` -eq 1 ] && (shell script)

for other Unix,BSD  
0 8 28-31 * * \[ \`echo \\\`cal\\\` | awk '{print $NF}'\` -eq 1 ] && (shell script)

另一种方法：  
单独靠crontab判断比较复杂，所以把判断部分写到执行脚本中

#!/bin/bash  
today=\`date +%d\`  
last\_day=\`cal | xargs | awk '{print $NF}'\`  
if \[ "$today" != "$last\_day" ];then     
 exit 1  
fi  
....  # other codes start from here