i am trying to use following commands in a shell script.. any suggestions to do it a correct way?

[root@testserver ~]# crontab -u oracle -e >> 0 0 * * * /usr/local/scrips/setup.sh
crontab: usage error: no arguments permitted after this option
 crontab [options] file
 crontab [options]
 crontab -n [hostname]

 -u <user>  define user
 -e         edit user's crontab
 -l         list user's crontab
 -r         delete user's crontab
 -i         prompt before deleting
 -n <host>  set host in cluster to run users' crontabs
 -c         get host in cluster to run users' crontabs
 -s         selinux context
 -x <mask>  enable debugging

Default operation is replace, per 1003.2
  • you can write directly to /var/spool/cron/crontabs/<username> it is the file opened with crontab -u afaik
    – mestia
    Aug 5 at 9:33
  • 2
    @mestia even if this option is supposed to work, it is strongly discouraged (see manpage of crontab) as there's no syntax check performed before installing the crontab which may lead to broken crontabs....
    – binarym
    Aug 5 at 9:35

The -e switch will make crontab interactive, which isn't the wished behaviour.

I suggest you use the crontab -u user file syntax. Below is an example:

root@c:~# crontab -l -u user
no crontab for user
root@c:~# echo "10 10 * * * /bin/true" >> to_install
root@c:~# crontab -u user to_install
root@c:~# crontab -l -u user
10 10 * * * /bin/true
root@c:~# crontab -l -u user > temp
root@c:~# echo "12 12 * * * /bin/false" >> temp
root@c:~# crontab -u user temp
root@c:~# crontab -l -u user
10 10 * * * /bin/true
12 12 * * * /bin/false
  • 3
    Listing the crontab is key, because crontab ... file replaces the entire crontab with the given file’s contents. Aug 5 at 9:55

Or in one line :

(sudo crontab -u user -l ; echo "*/5 * * * * /folder/script.sh") | sudo crontab -u user -
  • 2
    Watch out: parts before & after the pipe sign will begin execution in parallel, and if the sudo crontab -u user - truncates the user's old crontab before the sudo crontab -u user -l has managed to list it, the old crontab entries will be lost.
    – telcoM
    Aug 5 at 11:16
  • 1
    @telcoM in practice that’s not a problem here, because crontab validates the syntax of the file being installed before installing it — so it accumulates all the content elsewhere, to check it, before it replaces the existing crontab. Aug 5 at 11:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.