0

So I was checking my logrotate config for httpd, and, in the section postrotate ... endscript it has the following:

/sbin/service httpd reload > /dev/null 2>/dev/null || true

I understand the first one, if there is output, send it to /dev/null, but why the second entry?

I checked and a 2> means stderr to file. So, if I understand correctly, the first entry tells the script to send stdout to /dev/null and the second, stderr to /dev/null, is this correct?

As for the || true, why is it there?

Also, if &> means both stdout and stderr, can I replace both entries and just specify one time the following: /sbin/service httpd reload &> /dev/null ?

fizzy drink
  • 385
  • 4
  • 8
  • 22

1 Answers1

2

The first redirect just covers stdout - errors are usually sent to stderr instead so would still end up on the console without the second redirect which is telling the shell to send error output to /dev/null too.

The "2" is referring to a file descriptor: 0 is stdin, 1 is stdout and 2 is stderr, so > /dev/null is shorthand for 1> /dev/null assuming you usually mean stdout. Another way of doing the second redirect would be 2>&1 which means "send output to fd 2 to fd 1" (and as fd 1 is going to /dev/null this output will too).

|| true means "or true". This means that if the main command fails execution will not stop even if the shell running the script is set to stop on all failed commands. The true command (or shell built-in) does nothing but simply return a value that normally indicates success.

So essentially the line says "do X, but I don't care about the output, and if it fails just carry on and try the next thing".

David Spillett
  • 22,754
  • 45
  • 67
  • but if I use `&>`, can i have both sent to /dev/null at the same time? – fizzy drink Sep 24 '14 at 11:24
  • &> is bash specific I believe, where >, 1>, 2>, and so on are more standard. If you know your script will always run in an environment where bash v4+ is installed then yes, you can use &> instead. Logrotate will not be making that assumption though, in fact those scripts probably avoid all bashisms and use `/bin/sh` (which may or may not be bash, for instance current Debian uses dash by default as it is lighter and more efficient if you don't need bash's extras) instead of `/bin/bash` specifically. – David Spillett Sep 24 '14 at 11:31
  • Ok, thanks for that, I'm using CentOs (I didn't specify) so I'm not sure if &> is used. – fizzy drink Sep 24 '14 at 11:49
  • You can use &>, just make sure that you script explicitly uses bash (i.e. starts `#!/bin/bash` and not `#!/bin/sh`) other wise you'll get unexpected errors when you use it elsewhere. If you are feeling paranoid check the bash version early in your scripts to ensure you don't have something prior to version 4 (v4 was released in 2009 so older versions will be rare but you could still encounter them) as I think &> was added in that release. – David Spillett Sep 24 '14 at 14:16