Testing for File Characteristics

Problem

You want to make your script robust by checking to see if your input file is there before reading from it; you would like to see if your output file has write permissions before writing to it; you would like to see if there is a directory there before you attempt to cd into it. How do you do all that in bash scripts?

Solution

Use the various file characteristic tests in the test command as part of your if statements. Your specific problems might be solved with scripting that looks something like this:

#!/usr/bin/env bash
# cookbook filename: checkfile
#
DIRPLACE=/tmp
INFILE=/home/yucca/amazing.data
OUTFILE=/home/yucca/more.results

if [ -d "$DIRPLACE" ]
then
    cd $DIRPLACE
    if [ -e "$INFILE" ]
    then
        if [ -w "$OUTFILE" ]
        then
            doscience < "$INFILE" >> "$OUTFILE"
        else
            echo "can not write to $OUTFILE"
        fi
    else
        echo "can not read from $INFILE"
    fi
else
    echo "can not cd into $DIRPLACE"
fi

Discussion

We put all the references to the various filenames in quotes in case they have any embedded spaces in the pathnames. There are none in this example, but if you change the script you might use other pathnames.

We tested and executed the cd before we tested the other two conditions. In this example it wouldn’t matter, but if INFILE or OUTFILE were relative pathnames (not beginning from the root of the file system, i.e., with a leading “/”), then the test might evaluate true before the cd and not after, or vice versa. This way, we test right before we use the files. ...

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.