autolatex.sh

This is a simple script originally intended for monitoring several LaTeX source files and rebuilding and re-displaying the output whenever a file changes. It probably isn't the best script for the job, but it is also an example of how you can use inotifywait in Bash scripting to monitor files.

License

This tool is Public Domain. You are free to copy, redistribute, mangle and otherwise abuse this code. No warranty is provided and no guarantee as to its fitness for any particular purpose is made.

Source

#!/bin/bash

# AutoLaTeX - Re-run a LaTeX file and reload the output
# Copyright (c) 2008 Alan Briolat <alan@codescape.net>
#
# Wait for modifications to any of the files specified as arguments.  When an
# event is caught, run the BUILD program with the first file as its argument.
# If the build is successful, run the SHOW program with OUTFILE as the argument.
#
# Requires inotify-tools (more specifically, inotifywait).

# Various tools
BUILD="pdflatex -halt-on-error"
SHOW="evince"
WAIT="inotifywait -qq"

# Check that the bare minimum has been done to run this
if [ ! -n "$1" ] ; then
    echo "Usage: `basename $0` file1 [file2 ...]"
    exit
elif [ ! -e "$1" ] ; then
    echo "Cannot watch non-existent file: $1"
    exit
fi

# Get the main input file and output file names
TEXFILE="$1"
OUTFILE="${1/.tex/.pdf}"

# Drop the first argument
shift 1

# Wait on the input file (obviously)
WAITFILES="$TEXFILE"

# Add the remaining files to the wait list
if [ -n "$*" ] ; then
    for F in "$*" ; do
        if [ ! -e "$F" ] ; then
            echo "--- Dropping non-existent watch file: $F"
        else
            WAITFILES+=" $F"
        fi
    done
fi

echo "--- Watching: $WAITFILES"

while [ 1 ] ; do
    # Wait until the source file is modified
    $WAIT $WAITFILES
    # Because sometimes the file "disappears" for a fraction of a second...
    sleep "0.25"
    # Build the file once
    $BUILD "$TEXFILE"
    # If that failed, then go back to waiting
    if [ $? != 0 ] ; then
        echo -e "\033[1;31m!!! ERROR PROCESSING $TEXFILE\033[0m"
        continue
    fi
    # Build it a second time (resolve those table-of-contents things etc)
    $BUILD "$TEXFILE"
    echo -e "\033[1;32m+++ Processed $TEXFILE\033[0m"
    # Just in case it doesn't exist, check!
    if [ -e "$OUTFILE" ] ; then
        $SHOW "$OUTFILE"
    fi
done
Last modified September 16th, 2008 at 2:23 p.m.