Command of the Day: true and false
Table of Contents
Thought about doing this as two separate blog posts, but soon realized it would probably be the same post twice. As a software engineer, I deal with boolean values everyday. But never really thought about having boolean programs. Also, why would you want to make them into an entire program?
Overview⌗
If you’ve already rushed to your favorite terminal emulator and tried these commands, you might have been a bit disappointed.
true
false
…as nothing comes to STDOUT.
This is because it all comes down to the status code returned at the end of program’s execution.
I’ll cover status codes in a moment.
Taking a look at the man
pages, I think it sums up these programs quite succinctly.
true - do nothing, successfully
false - do nothing, unsuccessfully
While both true
and false
belong to the GNU coreutils collective, its most likely that you’re using your shell’s built-in
command -V true
true is a shell builtin
A Quick Dive into Status Codes⌗
Whenever a program exists, it returns a status code.
This is to show the success of the program’s execution.
This value is stored in $?
.
At the end of the day it basically comes down to this:
- 0 is success
- Non-zero is a failure (most will exit with a value of 1)
Depending on the situation, the exit status can give meaning. There isn’t an exit code standard but there are a few commonly used ones, but again, this could vary depending on the machines/applications.
Status Code | Meaning |
---|---|
1 | usually a catchall for general errors |
2 | misuse of shell builtins (according to Bash documentation) |
127 | “command not found” |
128 | invalid argument to exit |
130 | terminated by SIGINT (ctrl-c) |
Examples⌗
On the off chance something can throw an error, but you need to continue on regardless of success/failure, true
can be used to ensure the continuation of the script.
#!/usr/bin/env bash
set -eio pipefail
# will return a sucessful exit status if call_some_process fails
call_some_process || true
Conversely, if you need to fail and cancel out the success you can use
#!/usr/bin/env bash
set -eio pipefail
# will fail even if this is successful
go run main.go && false
This next one is a bit strange as it returns 1 in bash, but returns 0 in zsh.
$ f() { ! return; }; false; f; echo $?
Be careful, but for most common use cases, it will be consistent throughout shell environments.
Fun Fact!⌗
false
is the shortest utility within GNU coreutils, weighing in at just 2 LINES OF CODE. Define EXIT_STATUS
and then use the source code of true.c
.
#define EXIT_STATUS EXIT_FAILURE
#include "true.c"
References⌗
- [1] Why are true and false so large? | Stack Exchange
- [2] Exit Status | Bash Hackers Wiki
- [3] Decoded: false (coreutils) | MaiZure’s Projects