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.

5
  • this is cool - i'm going use this one day to update cron. very useful.
    – WEBjuju
    Commented Jan 15, 2018 at 15:44
  • 1
    Note that this is a common enough idiom that on debian(-derived) systems, the man page for crontab(1) includes notice about the handling of system default warning comments when using crontab -l | crontab -. Commented Jan 15, 2018 at 16:01
  • 2
    Possible duplicate of How does '-' work in bash redirection? Commented Jan 16, 2018 at 2: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. Commented Jan 16, 2018 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.
    Commented Jan 16, 2018 at 14:01

1 Answer 1

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.

2
  • 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.
    Commented Jan 15, 2018 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 | sed ... | cat >file does not hold true in the general sense. Commented Jan 16, 2018 at 13:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .