True or false?

Ryan asks what the point of the true and false programs are. By design those two programs do nothing, either successfully (for true) or unsuccessfully (for false).

Programs that do nothing might at first seem pointless. And if those programs were only ever run by themselves, they would be. However, they become useful tools to have when you start writing shell scripts.

It might not be apparent if your only Unix experience with shells is the command line, but the shell is actually a full-fledged programming language, albeit one with a fairly lean intrinsic feature set. Unix shells provide basic constructs for control flow and variables and such, but rely on other programs to do the “real” work.

In this context, the true and false programs can play the role as boolean values in conditional tests in shell scripts. For example, the following crude reimplementation of yes uses true:

#! /bin/sh
if [ -z $what ]; then
while true; do
    echo $what

The condition of a while loop is actually a command to execute; as long as that command is successful, the loop will continue.

It’s worth noting that the condition of the if also takes a command. Here, the command is [. Yes, that’s the name of a program on Unix. (Or technically, a link to the test program.)

Another use for test is in a makefile. Makefiles execute a series of commands for a target, and abort if any one of those commands fail. You can stick a “|| true” at the end of a command to get around this, like so:

    rm program 2>/dev/null || true
    rmdir tempfiles 2>/dev/null || true

make runs each line in the target using the shell, and gives up once one of the lines reports an error. The || does a short-circuiting logical or on the exit status of the two commands on either side. In this case, if the command on the left fails, it runs the command on the right and reports its exit status as the overall exit status of the command. The end result is that make sees the line as succeeding even if rm reported an error. If we didn’t do that, then in our example rmdir wouldn’t get called if rm failed.

Of course, neither of those examples is necessarily the best way to do things, but they serve their didactic purpose.

Now, if you’re wondering what the point is of trying to implement the functionality of true or false in as small a program as possible, it’s just for either curiosity’s sake and/or bragging rights. In particular, true and false are the simplest possible programs on Unix — all they do is quit immediately — and so any attempt to make the smallest program possible will necessarily reimplement their functionality.