Skip to content

Instantly share code, notes, and snippets.

@mayjs
Created February 8, 2018 11:33
Show Gist options
  • Save mayjs/906607b74005f66561cab58c12058b40 to your computer and use it in GitHub Desktop.
Save mayjs/906607b74005f66561cab58c12058b40 to your computer and use it in GitHub Desktop.
This simple shell script will find the closest tex root file upwards from a given location.
#!/bin/bash
# Usage example:
# if roottex=$(~/findroot.sh .); then; echo $roottex; else; echo No root found;fi
# This constant determines how many directories will be searched.
# A value of 0 will result in no searching at all, 1 will search the directory of the given file or the given directory
SEARCHDEPTH=3
## This part is only parameter validation
function showUsage {
echo USAGE: $0 FILENAME
echo " This script will find the nearest Latex root document to the given location"
echo " It will only search in parent directories, never in child directories"
}
# Check if something other than exactly one argument was given
if (( $# != 1)); then
(>&2 showUsage)
exit 1
fi
# Check if the given file does NOT exist
if [[ ! -e $1 ]]; then
(>&2 echo $1: File not found.)
(>&2 echo)
(>&2 showUsage)
exit 1
fi
## Start of actual logic
TEXFILE="$(realpath "$1")"
# Find the directory to start the search
# If the supplied path points to a file, start at the directory of that file
if [[ -f $TEXFILE ]]; then
TEXDIR="$(dirname "$TEXFILE")"
else
TEXDIR="$TEXFILE"
fi
# The searchTexRoot function takes 2 parameters:
# $1: The directory to search
# $2: The remaining search depth.
function searchTexRoot {
if (($2 > 0)); then
# Use find to find all .tex files in the current directory
# -maxdepth 1 essentially disables directory recursion
files=$(find "$1" -maxdepth 1 -path "*.tex" -print)
# Iterate over all files which where found
for f in $files; do
# Use grep to find a "\begin{document}" inside of the tex file.
# -q disables output and makes grep exit with 0 on the first hit
# -F makes grep interpret the given pattern as a fixed string
if grep -qF "\begin{document}" "$f"; then
echo $f
# Exit after the first hit to prevent outputting multiple files
exit 0
fi
done
# Continue to search as long as the directory name changes
nextdir="$(dirname "$1")"
if [[ "$nextdir" != "$1" ]]; then
searchTexRoot "$nextdir" $(($2 - 1))
fi
fi
}
# Start the recursive search
searchTexRoot "$TEXDIR" $SEARCHDEPTH
exit 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment