3

I know what the operators && and || do in Bash.

But recently I came across the following case in a shell script:

[[ test1 ]] && { test2 } || :

I am confused as to what does the || : (logical OR followed by :) in the above statement does?

Could anyone elaborate?

Biffen
  • 6,249
  • 6
  • 28
  • 36
  • 4
    [`:` is a command that does nothing](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#colon), so `command || :` is just a way to ‘ignore’ that `command` may fail. Especially useful with `set -e`. – Biffen Jun 12 '18 at 06:46

2 Answers2

3

One step at a time:

  • : is a shell builtin that is basically equivalent to the true command. If you're interested, there is a very good description of it's history and how it works on this question.

  • [[ test1 ]] tests for the presence of test1. (Normally, this would be a variable.)

  • { test2 } executes test2 in the current shell environment. (Normally, this would be a list of commands terminated with a newline or semicolon.)

  • && has a higher precedence then ||. Thus [[ test1 ]] && { test2 } will be evaluated before ||.

Putting it all together,

[[ test1 ]] && { test2 } || :

Means:

  • If test1 exists, then execute test2
  • If test1 doesn't exists, or if test2 fails, then return true (ie: $? == 0)

Things to note:

  • returned exit code ($?) is not the same as "return no errors"! If test2 fails, you might still see errors in the script's output, but the exit code of the entire command will always be true.

  • Errors when executing test2 will not terminate the script if it is executed under set -e.

UrsaDK
  • 854
  • 13
  • 27
0

cmd || : is a way to ignore an error caused by cmd. This is useful if the script is executed using set -e and you don't want it to be interrupted if cmd fails.

Maxime Chéramy
  • 17,761
  • 8
  • 54
  • 75