Testing for More Than One Thing

Problem

What if you want to test for more than one characteristic? Do you have to nest your if statements?

Solution

Use the operators for logical AND (-a) and OR (-o) to combine more than one test in an expression. For example:

if [ -r $FILE -a -w $FILE ]

will test to see that the file is both readable and writable.

Discussion

All the file test conditions include an implicit test for existence, so you don’t need to test if a file exists and is readable. It won’t be readable if it doesn’t exist.

These conjunctions (-a for AND and -o for OR) can be used for all the various test conditions. They aren’t limited to just the file conditions.

You can make several and/or conjunctions on one statement. You might need to use parentheses to get the proper precedence, as in a and (b or c), but if you use parentheses, be sure to escape their special meaning from the shell by putting a backslash before each or by quoting each parenthesis. Don’t try to quote the entire expression in one set of quotes, however, as that will make your entire expression a single term that will be treated as a test for an empty string (see Testing for String Characteristics).

Here’s an example of a more complex test with the parentheses properly escaped:

if [ -r "$FN" -a \( -f "$FN" -o -p "$FN" \) ]

Don’t make the assumption that these expressions are evaluated in quite the same order as in Java or C language. In C and Java, if the first part of the AND expression is false (or the first part true ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.