How to Test File Permissions with Bash  

Recently, I posted about basic permissions for Linux files; now let’s look at how to access those in a shell script. Testing file permissions is an essential part of enforcing an access control policy.

Two common ways to test files for readability, writability, zero size and so forth are the if and the test. For example, to print “Readable” if the file named readable is readable, we could do one of

If [[ -r readable ]]; then
echo Readable

[[ -r readable ]] && echo Readable

The first form is a full if construct. It allows multiple statements between the then and the fi. The second is based on the logical and operator &&. If the left side of the operator is true, the second side is executed (and if the first side is false, the second side isn’t executed).

There are multiple tests one can do on files and directories in the bash shell. There is a list of all file and string tests bash can do in the manual.

Some common file tests are:Bash file test operators

Here are some examples:

Example file tests

File tests with and

The && operator is logical and. It requires both sides to be true for the expression to be true. Thus since the file “writable” is both readable and writable, the message is printed. There is also a corresponding or operator: ||, and parenthesis for grouping. The ! operator is the logical not. If the expression following it is false, the result of the whole expression (with the !) is true. Thus the message that “private is NOT writable”.

File tests with parens

I’ve only scratched the surface of what one can do with bash test operators. There more file attributes that can be tested and there are tests for strings. Learning Tree offers a one-day shell scripting boot camp with far more information on tests, file permissions and other aspects of bash scripting. I also teach the system and network security course which discusses the concepts of properly securing files by setting file permissions.

If you use bash on Linux or Bash on Ubuntu on Windows as I did for these examples, I hope you found them useful.

To your safe computing,
John McDermott

Type to search

Do you mean "" ?

Sorry, no results were found for your query.

Please check your spelling and try your search again.