Why it makes sense for true
and false
to ignore their arguments
It's standard when writing Unix command line programs to make them check their arguments and complain if the usage is incorrect. It's reasonably common to do this even for programs that don't take options or positional arguments. After all, if your command is supposed to take no arguments, it's really an error if someone runs it and gives it arguments.
(Not all scripts, programs, and so on actually check this, because you usually have to go at least a little bit out of your way to look at the argument count. But it's the kind of minor nit you might get code review comments about, or an issue report.)
true
and false
are an exception to this, in that they more or
less completely ignore any arguments given to them. Part of this
behavior is historical; the V7 /bin/true
and /bin/false
were
extremely minimal, and when you're being minimal it's easiest to
not even look at the arguments. But beyond the history, I think
that this is perfectly sensible behavior for true
and false
because it makes them universal substitutes for other commands,
for when you want to null out a command so that it does nothing.
Want to make a command do nothing but always succeed? Simple: 'mv
command command.real; ln -s /bin/true command
'. Want to do the
same thing but have the command always fail? Use false
instead
of true
. Sure, you can do the same thing with shell scripts that
deliberately ignore the arguments and just do 'exit 0
' or 'exit
1
', but this is a little bit simpler and matches the historical
behavior.
(You can also do this in shell scripts as a way of creating a 'don't actually do anything' mode, but there are probably better patterns there.)
On that note, it's interesting to note that although GNU true
and
false
have command line options that will cause them to produce
output, there is no way to get them to return the wrong exit status.
And while they respond to --help
and --version
, they silently
ignore other options (as opposed to, say, reporting a syntax error).
(This entry was sparked by Zev Weiss's mention of true
in his
comment on this entry.)
Sidebar: true
and false
in V7
In V7 Unix, true
is an empty file and false
is a file that is
literally just 'exit 1
'. Neither has a #!
line at the start of
the file, because that came in later. That
true
is empty instead of 'exit 0
' saves V7 a disk block, which
probably mattered back then.
|
|