Bash Boilerplate

A collection of pieces of bash script code that do certain things.

Change to directory if possible

cd $DIR || {
  echo "Cannot change to necessary directory." >&2
  exit $E_XCD;
}

Iterate over files

# Using glob
FILES="/var/log/*.log"
for file in $FILES
do
  echo "$file"
done

# Using ls (here sorted after ctime)
FILES=$( ls -c /var/log/*.log )
for file in $FILES
do
  echo "$file"
done

Get the number of matches in a file glob

FILES=(/var/log/*.log)
FILECOUNT=${#FILES[*]}

Extract path, filename and extension

FILEPATH="../.we-ird_/p├ąth/file.name.txt"
FILEDIR="${FILEPATH%/*}"
FILENAME="${FILEPATH##*/}"
EXTENSION="${FILEPATH##*.}"
NOEXTENSION="${FILEPATH%.*}"

Get the directory of the bash script

DIR=$(dirname $(readlink -f "$0"))

Get the number of lines in a file

LINECOUNT=`wc -l $FILE | awk '{ print $1 }'`

Tests

if [ -z "$1" ]
then
  echo "first parameter is null"
fi

if [ -n "$1" ]
then
  echo "first parameter is not null"
fi

(see also man test)

Validating arguments

# Match an argument against a regex
if echo "$1" | grep "^[0-9]\+$" > /dev/null
then
    echo "$1 is a postitive integer"
else
    echo "$1 is not a positive integer"
fi

# Loop through all arguments
while [ "$#" -gt "0" ]
do
    if [ "$1" = "-a" ]
    then
        if echo "$2" | grep -e "^valid_value1$" -e "^valid_value2$" > /dev/null
        then
            echo "The value of flag '-a' is $2"
            shift
        else
            echo "Invalid value for flag '-a'"
        fi
    elif [ "$1" = "-b" ]
    then
        echo "Flag '-b' is on."
    fi
    shift
done

A good bash guide
Pure bash bible