Skip to content
Vince Buffalo edited this page Oct 22, 2013 · 2 revisions

Robust Bash Scripts

Should be loud. Use:

set -e
set -u
set -o pipefail

These come from the article Writing Robust Bash Shell Scripts and Shaun Jackman.

Checking File and Directories Exist

I use:

check_file_exists() {
    if [ ! -f "$1" ]; then
        echo "[trim.sh] error: file '$1' does not exist." >&2
        exit
    fi
}

check_dir_exists() {
    if [ ! -d "$1" ]; then
        echo "[trim.sh] error: directory '$1' does not exist, creating it." >&2
        mkdir -p $1
    fi
}

Note, you may wish to use something other than -f, which is for regular files only (i.e. not named pipes). -e is more general. There are many other valid Bash test operations.

Check Programs are in Path

Do no use which — it is not portable. command -v works better. For example:

((command -v scythe && command -v sickle && command -v seqqs) > /dev/null) || \
(echo "[trim.sh] error: either scythe, sickcle, or seqqs is not in your $PATH" && exit 1)

Time Steps of Your Script

Use:

# time trimming process process
T="$(date +%s)"

# ... stuff goes here

T="$(($(date +%s)-T))"
echo "[trim.sh] $SAMPLE_NAME took seconds: ${T}"
Clone this wiki locally