0

what does "2>&1 || :" mean in shell script?

gzip some.log 2>&1 || :

I know what "2>&1" means. but what is the meaning of "|| :" that follows?

user7024
  • 311
  • 2
  • 10
  • `||` means "or", same as it does in any other context. `:` is the same command as `true`. – Charles Duffy Aug 10 '21 at 15:36
  • So it's identical to `gzip some.log 2>&1 || true` – Charles Duffy Aug 10 '21 at 15:36
  • 2
    As for _why_ someone might want to use `|| true`, any chance your script might be running with `set -e`? (Note that this is not generally considered a good idea; for a full discussion of why `set -e` does more harm than good to reliability and comprehensibility, see [BashFAQ #105](http://mywiki.wooledge.org/BashFAQ/105), particularly including the exercises -- or the list of ways different shells implement it differently at https://www.in-ulm.de/~mascheck/various/set-e/) – Charles Duffy Aug 10 '21 at 15:38
  • @CharlesDuffy yes, `gzip some.log 2>&1 || :` is running with `set -e`. then it makes sense. thanks – user7024 Aug 10 '21 at 15:41
  • [This question](https://unix.stackexchange.com/q/325705/118235) on [unix.se] is relevant. – Benjamin W. Aug 10 '21 at 16:02
  • Or [this one](https://stackoverflow.com/q/28773880/3266847https://stackoverflow.com/q/28773880/3266847) – Benjamin W. Aug 10 '21 at 16:04
  • 2 is the standard error output, `2>&1` is saying "redirect errors to the same standard output which is 1", by default errors are redirected to 1, I don't know why `2>&1` is used there, I think with or without it the output is the same – Talel BELHADJSALEM Aug 10 '21 at 16:10
  • @BelHadjSalemTALEL, the OP (in the first half of the last paragraph of the question) says they already understand `2>&1`, and the `|| :` is the only part that is novel to them. And yes, the output is the same either way, but which descriptor it's written to can matter -- if one is piping to `less`, for example, one can want error messages to show up in the pager. – Charles Duffy Aug 10 '21 at 17:39
  • @CharlesDuffy , I didn't notice that in the question, my mistake. And good information for me to learn, thanks a lot – Talel BELHADJSALEM Aug 10 '21 at 19:31

0 Answers0