1

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.

Murda Ralph
  • 11
  • 1
  • 2

2 Answers2

1

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
  • using tee -a we are telling tee to append @reboot /path/to/file.sh at the end of this file instead of overwriting it.
  • if it's not there it will be created.
Ravexina
  • 55,668
  • 25
  • 164
  • 183
1

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 append text on one line.


Note: unlike writing to /var/spool/cron/crontabs directly, this approach doesn't need sudo (because crontab is setuid).

steeldriver
  • 136,215
  • 21
  • 243
  • 336