Operators in bash Conditional Expressions

How do I find out what [ -f file ] does? I can’t seem to Google it...

Jackson Pauls By Jackson Pauls

Say you’re new to Linux shell scripting, and have found a bash script that does something you want. Well almost, you need to tweak it a bit, and for that you have to understand it. You’re struggling to understand what -f does in a piece of code that looks like this:

if [ -f some_filename ]
then
  # do something
fi

Your first instinct might be to search Google for something like “shell script -f”, but that only gives you generic pages about shell scripts. “bash script -f”? Same issue.

You’re not alone. Every month, thousands of people search for things like:

And variants like:

But the search results for those queries all suck.

This is because a dash (-) excludes results for the following search term. So a search for:

shell scripting -f
means:
search for shell scripting, but exclude results containing “f”

And that’s not at all what we want.

Fortunately, the fix is simple: if you need to search for something starting with a dash (a.k.a. a "hyphen" or "minus"), stick quotes around it:

shell scripting "-f"

It’s that easy, check out some example Google results.

Operators and Conditional Expressions

-f, -x, -nt and friends are all operators for bash conditional expressions:

-f
tests if a file exists
-x
tests if a file exists and is executable
-h
tests if a file exists and is a symbolic link (Why h? I don’t know.)
-nt
tests if one file is newer than another
-n
tests if the length of a string is non-zero
-eq
tests if two arguments are equal
So the the expression
[ -f some_filename ]
is true if a file called some_filename exists.

There are many other bash operators, the complete list is under Conditional Expressions on the bash man page.

Incidentally, the dash in -z in a Google search is also an operator, as are the quotes around "-z". Discover more of these in Google’s help on search operators.