有一个 shell 脚本,需要设置 crontab,简化之后如下
#!/bin/bash
set -e
rm /var/spool/cron/crontabs/root -rf
(crontab -l; echo "@reboot /etc/init.d/init.sh";) | crontab -
发现使用 sudo 运行之后,/var/spool/cron/crontabs/root 的内容为空(如下)
# DO NOT EDIT THIS FILE - edit the master and reinstall.
# (- installed on Mon Jan 17 10:30:27 2022)
# (Cron version -- $Id: crontab.c,v 2.13 1994/01/17 03:20:37 vixie Exp $)
修改脚本,把 set -e 去掉,运行结果正常,此时 /var/spool/cron/crontabs/root 的内容如下
# DO NOT EDIT THIS FILE - edit the master and reinstall.
# (- installed on Mon Jan 17 10:31:57 2022)
# (Cron version -- $Id: crontab.c,v 2.13 1994/01/17 03:20:37 vixie Exp $)
@reboot /etc/init.d/init.sh
注意,这里多出了最后一行: @reboot /etc/init.d/init.sh,这才是预期的结果
所以觉得很奇怪,是 set -e 和 crontab 命令有冲突吗