crontab重定向不生效的问题描述
问题背景
在Linux系统中,周期性执行的任务通常由cron守护进程负责处理[ps -ef|grep cron]。该进程会读取特定的配置文件,其中定义了需要执行的命令及其调度时间。
这类配置文件被称为“crontab”,即“cron table”的缩写。
最近在配置crontab添加了一项定时任务,该任务执行后会产生正常输出。为了捕获执行过程中的异常信息以便排查问题,我在crontab中编写了如下命令:
01 09 * * * cd /opdir/test/ && ./test.sh &>>test.log
上述命令意图清晰:每天9:01执行test.sh脚本,并将脚本的标准错误输出(stderr)和标准输出(stdout)全部重定向至test.log文件。然而实际运行发现,虽然脚本成功执行,但test.log文件始终为空。
为了解释并解决这一现象,首先需要梳理Linux系统中重定向的基本原理。
基本概念
在Linux系统中:
1代表标准输出(stdout),默认流向屏幕;
2代表标准错误输出(stderr),默认也流向屏幕。
日常开发中,我们常使用以下方法将脚本的执行结果重定向到文件:
bash test.sh >test.out //脚本的标准输出写入到文件test.out ,标准错误输出直接打印在屏幕 等价于:bash test.sh 1>test.out
bash test.sh >test.out 2>&1 //标准输出和标准错误输出都写入到test.out并且不会互相覆盖,等价于 bash test.sh &>test.out
bash test.sh >test.out 2>test.out //标准输出和标准错误输出都写入到test.out,会出现互相覆盖的问题,正常情况不推荐这样使用
bash test.sh &>test.out //等价于第二种方法
对比上述几种重定向方式的效果:
第一种情况:错误信息显示在屏幕,正常输出写入test.out文件。
root@mengalong:~/opdir/mengalong/t/t# cat test.sh
#!/bin/bash
t
date
root@mengalong:~/opdir/mengalong/t/t# bash test.sh >test.out
test.sh: line 2: t: command not found
root@mengalong:~/opdir/mengalong/t/t# cat test.out
Wed Oct 31 11:07:24 CST 2026
第二种情况:错误信息和正常输出均被重定向到test.out文件中。
root@mengalong:~/opdir/mengalong/t/t# bash test.sh >test.out 2>&1
root@mengalong:~/opdir/mengalong/t/t# cat test.out
test.sh: line 2: t: command not found
Wed Oct 31 11:09:02 CST 2026
第三种情况:错误信息和正常输出分别写入test.out,会导致文件内容互相覆盖。
root@mengalong:~/opdir/mengalong/t/t# bash test.sh >test.out 2>test.out
root@mengalong:~/opdir/mengalong/t/t# cat test.out
Wed Oct 31 11:10:36 CST 2026
ot found
第四种是特殊情况,需比较 bash test.sh 2>&1 >test.out 与 bash test.sh >test.out 2>&1 的区别:
root@mengalong:~/opdir/mengalong/t/t# bash test.sh 2>&1 >test.out
test.sh: line 2: t: command not found
root@mengalong:~/opdir/mengalong/t/t# cat test.out
Wed Oct 31 11:12:13 CST 2026
仅将 2>&1 置于 >test.out 之前,结果却未如预期般将错误和正常输出都存入test.out。原因在于 bash test.sh 2>&1 >test.out 中,当执行 2>&1 时,标准错误被重定向至当时的标准输出位置,而此时标准输出默认指向屏幕,因此实际效果等同于错误输出仍显示在屏幕,并未进入文件。这说明重定向的顺序至关重要。
问题解决
回顾前文提到的crontab任务配置:
01 09 * * * cd /opdir/test/ && ./test.sh &>>test.log
依据前述原理分析,该写法看似等价于 ./test.sh >test.log 2>&1,理论上应将所有输出重定向至test.log。但实际情况是test.log依然没有内容。
根本原因在于crontab默认使用的Shell环境是 /bin/sh,而 /bin/sh 并不支持 &>>test.log 这种重定向语法,从而导致重定向失败,文件内容为空。
因此,解决此问题的方法是修改crontab中的重定向语法:
01 09 * * * cd /opdir/test/ && ./test.sh >>test.log 2>&1
补充说明
若crontab执行脚本时未进行重定向,系统默认会将输出作为邮件发送给当前用户。邮件通常存储在 /var/mail/$user 路径下,若不及时清理,可能占满服务器根分区,进而导致机器无法登录。因此,推荐的crontab命令写法应包含重定向逻辑:
01 09 * * * cd /opdir/test/ && ./test.sh >>test.log 2>&1
具体增加了 >>test.log 2>&1 部分
总结
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对本站的支持。