Created
May 14, 2025 09:32
-
-
Save ferdiu/5e798ae827eac79197996c6d7637e04f to your computer and use it in GitHub Desktop.
A simple BASH script to listen to file changes and automatically recompile LaTeX documents (supports Fedora toolbox containerization)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
USE_TOOLBOX=0 | |
# Check whether pdflatex command is available | |
if ! command -v pdflatex &> /dev/null; then | |
# If not, test if Fedora toolbox named latex exists | |
if command -v toolbox &> /dev/null && toolbox list | grep -q latex; then | |
USE_TOOLBOX=1 | |
else | |
echo "pdflatex command not found. Please install it or create a Fedora toolbox named latex." | |
exit 1 | |
fi | |
fi | |
compile_latex() { | |
pdflatex -shell-escape -synctex=1 -interaction=nonstopmode -file-line-error "$1" | |
# Print a message saying that the compilation is unsuccessful if so | |
if [ $? -ne 0 ]; then | |
echo -e "\033[31merror\033[0m: compilation unsuccessful (see output up here for details)" | |
fi | |
} | |
usage() { | |
echo "Usage: $0 <file.tex> [<other files to watch for changes>]" | |
echo "This script watches for changes in the specified .tex file" | |
echo "and its dependencies, and compiles the .tex file whenever" | |
echo "a change is detected." | |
echo | |
echo "When pdflatex is not available, a Fedora toolbox named latex is" | |
echo "required." | |
echo | |
echo "The firs argument should be the \"main\" .tex file." | |
echo "Any other arguments will be passed to the inotifywait command" | |
echo "just to check if it changes and to trigger the compilation." | |
echo "This is useful for example to watch for changes in the bibliography." | |
} | |
# Check if no arguments were passed | |
if [ "$#" -lt 1 ]; then | |
echo "error: no file specified." >&2 | |
usage >&2 | |
exit 1 | |
fi | |
# Check if first argument is just "--help" or "-h" | |
if [ "$1" == "--help" ] || [ "$1" == "-h" ]; then | |
usage | |
exit 0 | |
fi | |
# Check if first argument is a tex file | |
if [ ! -f "$1" ] || [[ ! "$1" =~ \.tex$ ]]; then | |
echo "error: first argument must be a .tex file." >&2 | |
usage >&2 | |
exit 1 | |
fi | |
# Execute | |
if [ "$USE_TOOLBOX" -eq 1 ]; then | |
toolbox run -c latex "$0" "$@" | |
exit 0 | |
else | |
while inotifywait -e close_write "$@"; do compile_latex "$1"; done | |
exit 0 | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment