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"

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. Commented Feb 21, 2020 at 9:52

1 Answer 1


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
    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"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .