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.

  • 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) 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? – G-Man Says 'Reinstate Monica' Jan 16 '18 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. – 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
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.

  • 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 | sed ... | cat >file does not hold true in the general sense. – roaima Jan 16 '18 at 13:41

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.