Else

It may be that you want to cat the file if at all possible, but if it can’t be done, then continue execution of the script. One way to do this would be to have two tests. Here is the first test:

if [ -r "$1" ]; then cat "$1"; fi 

followed by the opposite test (! reverses the result of the test):

if [ ! -r "$1" ]; then echo "File $1 is not readable – skipping. "; fi

But that is quite cumbersome and prone to errors. If you later replace the test with -s, for example, you would have to change it in two places. So, the else statement comes into play:

#!/bin/bash
# Check for likely causes of failure
if [ ! -r "$1" ]; then
  echo "Error: $1 is not a readable file."
else
  cat "$1"
fi

You can make this easier to read by taking out the exclamation point (!) and reversing the order of the statements:

#!/bin/bash
# Check for likely causes of failure
if [ -r "$1" ]; then
  cat "$1"
else
  echo "Error: $1 is not a readable file."
fi

This is more easily readable, and more robust, than the previous scripts. It is often the case that the cleanest solution is actually easier to read than a more convoluted solution.

Get Shell Scripting: Expert Recipes for Linux, Bash, and More 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.