True and false (commands)
Shell commands that exit immediately with a 0/1 status
true and false are shell commands that exit immediately with exit status 0 or 1, respectively. As a script sets its process exit status to the value of the last command it runs, these commands can be used to set the exit status of a script run. All Unix shells interpret an exit status of zero as success and non-zero (usually) as failure, so true sets success and false sets failure.
The commands are available in Unix-like operating systems.
01Use
The commands are usually employed in conditional statements and loops of shell scripts. For example, the following script repeatedly executes echo hello until interrupted:
while true do echo hello doneThe commands can be used to ignore the success or failure of a sequence of other commands, as in the example:
make … && falseSetting a user's login shell to false, in /etc/passwd, effectively denies them access to an interactive shell, but their account may still be valid for other services, such as FTP. (Although /sbin/nologin, if available, may be more fitting for this purpose, as it prints a notification before terminating the session.)
The programs accept no command-line arguments except that the GNU version accepts the typical --help and --version options.
02Null command
The true command is sometimes substituted with the very similar null command, written as a single colon (:). The null command is built into the shell, and may therefore be more efficient if true is an external program (true is usually a shell built in function). We can rewrite the upper example using : instead of true:
while : do echo hello doneThe null command may take parameters, which are ignored. It is also used as a no-op dummy command for side-effects such as assigning default values to shell variables through the ${parameter:=word} parameter expansion form. For example, from bashbug, the bug-reporting script for Bash:
: ${TMPDIR:=/tmp} : ${EDITOR=$DEFEDITOR} : ${USER=${LOGNAME-`whoami`}}03Null smileys
Either true or : can be used as a replacement for cat /dev/null, so there are 3 "null smileys":
- :> - create a file or empty it if it already exists;
- :>> - create a file if it doesn't exist, unlike touch it does not change the timestamp of existing file;
- :| - can be used instead of < /dev/null
Such usage is similar to the IEFBR14's standard usage.
Sources and credits
This article is adapted from the Wikipedia article “True and false (commands)”, written by its contributors and licensed under CC BY-SA 4.0. Fathomly has changed the layout, removed citation markers, navigation and maintenance notices, and adjusted punctuation. This adapted version is shared under the same license. For references, see the original article.
Fathomly is not affiliated with or endorsed by the Wikimedia Foundation. Spotted a problem? Tell us.