Last Updated: February 25, 2016
·
4.931K
· gildas

That noop operator in bash

Many people ask use case of the : operator in bash and wonder if there is any use for it.

Here is one good usage for what it is worth.

Quite often we need a dry run mode in bash scripts. Most of the time, we end up with rather ugly tests to avoid executing code.

The solution is to write something like this:

NOOP=

# parse arguments, and if needed turn on NOOP:
# (other arguments have been ignored)
while :; do
  case $1 in
    --noop|--dry-run|-n)
      NOOP=:
      ;;
  esac
  shift
done

# Now "mark" the dry-run code like this:
$NOOP sudo mkdir -p /var/log/myapp

Why does it work?<br>
If NOOP equals ":", then the last line becomes:<br>
bash : sudo mkdir -p /var/log/myapp
<br>
Since : resolves as true, the rest of the line is not executed.