What is the point of the "null" operator in a BASH script? I understand that it is used as a placeholder following an if
command when you have nothing to say, but need a command to allow the program to run properly. But what is the overall use for it? When would you use it? When does it make sense to use it?
It's sometimes useful to allow parameter expansions side-effects to occur.
For example, setting a default value
You can also use it for endless loops:
You can use it to create a file without running a program::
This is infinitesimally faster than
touch /path/to/file
(since it doesn't require running thetouch
program) and may be marginally more portable than just plainwhich seems to work on many systems. Similarly, it can be used to check whether you have write access to a file:
although this, also, can generally be done without the
:
. Caveats:(See the linked question for reasons why this is more reliable than
if [ -w /path/to/file ]
.)Way back, in Unix V6 and Thompson Shell, the
:
was actually used as part of thegoto
statement. According to the manual, it originally appeared in version 3 of Unix:Nowadays, in
bash
, it's used as a no-op operator, returning success. Indeed, if you look at the source code, you'll see that bothtrue
and:
use same function,int colon_builtin()
, underneath. There's no:
non-builtin command, and/bin/true
is actually a fairly large command for what it does.:
could be used anywheretrue
is used, for example incommand_that_can_fail || true
, though that's likely to confuse non-experts. Read more about it here.You can use it on the positive test of an
if
command when you only want to do something on the negative side. For example:Without the
:
bash would generate a syntax error.This is an oversimplified example. Generally you would use such a technique in preliminary coding when you haven't written that code segment yet and just need something that doesn't generate an error.
I just used it in a script with SSH commands to keep the script from erroring out.
In this case, I want to see if a user can connect to a set of servers. If the connection is OK, the remote host will echo OK. If the connection fails, SSH will respond with the error. However, I want my script to exit with 0 and not the value of the SSH command if it fails. So essentially I trap the SSH error by ORing it
||
with the null command:
. Looks like this:That way I get the output from SSH but not the error code: