0

My script loops through all subsubdirectories and calls pdflatex command on all .tex files:

#!/usr/bin/env bash

shopt -s globstar

for d in ./*/**/*.tex; do
  echo pdflatex "$d"
done

My question

How to set the current working directory to the current subsubdirectory in the loop?

Similar question: How to set current working directory to the directory of the script?

Why I ask

My .tex files contain relative path and that's why the compiler only works if the current working directory is the directory where the file is.

  • Please edit question to define current (current working directory =? current directory). And give an example of what you want it to do. – ctrl-alt-delor Feb 21 at 9:52
4

You need to put the cd command inside the loop. The gotcha is that your paths are relative to your current directory, so the working directory must be reset back to the starting point at the beginning of each iteration in order for cd to work with your relative path. The ( ... ) subshell does that for us (the directory change lasts only for the scope of the subshell).

#!/usr/bin/env bash
shopt -s globstar

for d in ./*/**/*.tex
do
    dir="${d%/*}"     # Strip the *.tex pathname back to the containing directory
    tex="${d##*/}"    # Strip the *.tex pathname back to just the filename

    echo "Will process $tex in the subdirectory $dir" >&2
    (
        cd "$dir" || exit
        pdflatex "$tex"
    )
done
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.