Question: I would like to integrate a sanity test in my `Makefile` that builds multiple PDFs. I would like to count and compare the number of pages generated based on what `xelatex` outputs during/after the run, compare it an expected value and stop `make` to see if layout changes accidentally created too many / too few pages. What is the best/easiest way to do that?

I could `grep` for the usual page counter in the output, e.g. `[1][2][3]`, but that is prone to errors and often this counter is 1 page higher than the resulting PDF - in above example it counts to `[3]`, but the PDF contains only 2 pages.

I would like to avoid to check the PDF itself in a separate step so I don't have to "guess" its filename (which is generated in my case). In case that makes a difference, I need a solution for `xelatex`.

Answer: 
There are several ways for knowing the number of pages in a PDF file.

1. Grep the log file for `Output written` that will return something like

```
Output written on test.pdf (18 pages, 74251 bytes).

```

(independently of the page numbering)
2. Use `pdfinfo` (that comes with Poppler), so `pdfinfo test.pdf|grep Pages` will output something like

Pages: 18
3. Use `qpdf --show-npages test.pdf` that just outputs `18`.
4. Check this question and the answer by Heiko Oberdiek [Get number of pages of external PDF](https://tex.stackexchange.com/questions/198091/get-number-of-pages-of-external-pdf)
You can write it from within `xelatex` to an external file, e.g. `\jobname.pp`:

```
\documentclass{article}
\usepackage{totpages}
\usepackage{blindtext}
\AtEndDocument{%
    \newwrite\tempfile\newpage
    \immediate\openout\tempfile=\jobname.pp
    \immediate\write\tempfile{\theTotPages}%
    \immediate\closeout\tempfile}
\begin{document}

\blinddocument \newpage \blinddocument

\end{document}

```