I have a .sh that executes a command. I want to use crontab -e and enter into the file @reboot /path/to/command.
How do execute this in one command instead of separately running crontab -e then manually insert the line and then saving the file.
I have a .sh that executes a command. I want to use crontab -e and enter into the file @reboot /path/to/command.
How do execute this in one command instead of separately running crontab -e then manually insert the line and then saving the file.
When you use crontab -e
a file will be created at /var/spool/cron/crontabs/
which its name is equal to your uesername.
So just redirect your desired line to this file:
echo "@reboot /path/to/file.sh" | sudo tee -a /var/spool/cron/crontabs/$USER
tee -a
we are telling tee
to append @reboot /path/to/file.sh
at the end of this file instead of overwriting it.Probably the right way to do it - as explained in How to programmatically add new crontab file without replacing previous one - is to dump the existing crontab to a temporary file, modify it, then read it back in. For example:
cmd='@reboot /path/to/file'
tmpfile=$(mktemp) && crontab -l > "$tmpfile"
cmd='@reboot /path/to/command'
grep -Fxq "$cmd" "$tmpfile" || echo "$cmd" >> "$tmpfile"
crontab "$tmpfile" && rm -- "$tmpfile"
A "quick'n'dirty" option - if you don't care about checking - would be
crontab -l | sed '$a@reboot /path/to/command' | crontab -
assuming GNU sed, which allows a
ppend text on one line.
Note: unlike writing to /var/spool/cron/crontabs
directly, this approach doesn't need sudo
(because crontab
is setuid).