Tips

Boolean Variables In Shell Scripts

Posted on July 6, 2010. Filed under: Tips |

Technically, there is no variable typing in shell scripts.  In most shells, variables are just text strings unless and until evaluated in a different context, most often a numeric context.

Some shells support limited variable typing via their “typeset” command, but that capability is far from universal.

Given that many scripts use variables as flags to indicate some condition was met or not met, it would make things easier if there was a type BOOLEAN.  Let’s look at a typical example:


FILE_FOUND=n
# ... some processing to locate the file
    # File found, set the flag
    FILE_FOUND=y
    # ...
if [[ $FILE_FOUND = y ]]
then
    # process the file...
fi

That’s actually just fine, but, as with other languages, I prefer to use boolean variables for cleaner code.

Even though there is, technically, no such thing, it is quite easy to implement.  It looks like this:


FILE_FOUND=false
# ... some processing to locate the file
    # If found, set the flag
    FILE_FOUND=true
    # ...
if $FILE_FOUND
then
    # process the file...
fi

This works because “true” and “false” are actually commands, so $FILE_FOUND executes the “true” or “false” command.  “true” always returns 0 and “false” always returns 1.  This technique works in all bourne-style shells.

Execution-wise, it really doesn’t make any difference, but I like the cleaner look to the code.

Kimball

Read Full Post | Make a Comment ( None so far )

Liked it here?
Why not try sites on the blogroll...