In bash
every variable is essentially a string (or an array or a function, but let's talk about regular variables here).
The conditions are parsed based on the return values of the test commands -- the return value is not a variable, it's an exit state. When you evaluate if [ ... ]
or if [[ ]]
or if grep something
or anything like that, the return value 0 (not string 0, but exit status 0 = success) means true and the rest mean false (so, exactly the opposite from what you are used to in compiled programming languages, but because there is one way to succeed and many ways to fail, and the expected outcome of execution is usually success, 0 is used as the most common default result if nothing goes wrong). This is very useful because any binary can be used as a test - if it fails, it's false, otherwise it's true.
true
and false
programs (usually overridden by builtins) are just usefull little programs that do nothing -- true
succeeds at doing nothing, and exits with 0, while false
tries doing nothing and "fails", exitting with 1. Sounds pointless but it's very handy for scripting.
As for how to pass truthfullness around, it's up to you. It's quite common to just use "y" or "yes" for truth and use if [ x"$variable" = x"yes" ]
(appended the dummy string x
because if $variable
happens to be zero length, this protects from creating a bogus command if [ = "yes" ]
which doesn't parse). It may also be useful to simply use an empty string for false, and use [ -z "$variable ]
to test if it's zero-length (or -n
for it to be nonzero).
Anyway, it's quite rare to actually need to pass around boolean values in bash
- it's much more common to simply exit
on failure, or return a useful result (or zero if something goes wrong, and test for empty string), and most of the cases can test for failure directly from the exit statatus.
In your case, you want a function that will act as any other command (therefore, return 0 on success), so your last option seems the right choice.
Also, you may not even need return
statement. If the function is simple enough, you can use the fact that it simply returns the status of the last executed command in the function. So your function can simply be
drive_xyz_available() {
[ -e /dev/disk/by-uuid/whatever ]
}
if you are testing for existence of a device node (or grep /proc/mounts
to check if it's mounted?).
help true ; help false ; help exit