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:
- shell script -x
- shell script -h
- shell script -nt
And variants like:
- bash script -gt
- shell scripting -n
- shell scripting -z
- shell scripting -eq
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 -fmeans:
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:
- tests if a file exists
- tests if a file exists and is executable
- tests if a file exists and is a symbolic link (Why h? I don’t know.)
- tests if one file is newer than another
- tests if the length of a string is non-zero
- tests if two arguments are equal
is true if a file called some_filename exists.
[ -f some_filename ]
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.