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:

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

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:

# ... some processing to locate the file
    # If found, set the flag
    # ...
    # process the file...

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.



Make a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

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

%d bloggers like this: