2

I'm writing a bash script which, among other things, will edit crontab on another server. The way I figured out how to do this is with:

crontab -l | sed <stuff> | crontab -

It does what I need it to do, but I'm still not sure how. What exactly does "crontab -" do? When I run it by itself from the shell, it takes over the shell until I hit ctl+c, but doesn't seem to do anything. Is its only purpose to overwrite cron contents with whatever's passed from stdin? I can't seem to find any documentation on it.

Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
Ben C.
  • 135
  • 3
  • this is cool - i'm going use this one day to update cron. very useful. – WEBjuju Jan 15 '18 at 15:44
  • 1
    Note that this is a common enough idiom that on debian(-derived) systems, the [`man` page for `crontab(1)`](https://manpages.debian.org/jessie/cron/crontab.1.en.html) includes notice about the handling of system default warning comments when using `crontab -l | crontab -`. – user4556274 Jan 15 '18 at 16:01
  • 2
    Possible duplicate of [How does '-' work in bash redirection?](https://unix.stackexchange.com/questions/417377/how-does-work-in-bash-redirection) – G-Man Says 'Reinstate Monica' Jan 16 '18 at 02:49
  • 1
    Personally I would prefer something like `crontab -l >.crontab; sed ... .crontab | crontab`, which would leave me a copy of the original in case my `sed` command mangled the data irrecoverably. – roaima Jan 16 '18 at 13:44
  • @roaima I've already got that functionality in the command, using tee to save a copy of crontab. I just left it out for the sake of brevity. – Ben C. Jan 16 '18 at 14:01

1 Answers1

5

One syntax for crontab is

crontab <file>

Per Usage of dash (-) in place of a filename your usage of the - is to take stdin which in this case is the stdout coming from sed which is then feeding in to replace the <file> argument and replace the contents of cron instead of from the file you are giving it the stdin that is acting as that file.

WEBjuju
  • 496
  • 2
  • 4
  • 13
  • 1
    This is exactly the information I was looking for. Makes sense now why I couldn't find it in the cron documentation. Thanks! – Ben C. Jan 15 '18 at 15:51
  • One final missing part is to note that the `crontab` command does not replace any of its cron data until it has received everything from _stdin_. (So if you start typing, and then Ctrl/C out, you haven't lost the previous/current data.) This is peculiar to `crontab` and the idiom `cat file` does _not hold true_ in the general sense. – roaima Jan 16 '18 at 13:41