I have a problem with putting output of following instructions (instruction works) into variable:

pdftk file.pdf dump_data | grep NumberOfPages | awk '{print $2}'

when I do for example:

VARIABLE=$( pdftk file.pdf dump_data | grep NumberOfPages | awk '{print $2}' ) | echo $VARIABLE 

it doesn't show me the value of variable... May somebody tell what am I doing wrong? Thanks

3 Answers 3


You should use:

; echo $VARIABLE

Instead of the last pipe.

  • This does answer the question. It might be even more useful if you could expand on why the pipe didn't work, in addition to pointing out the working alternative
    – Fox
    Commented Dec 29, 2017 at 21:57
  • ; means next command just as if you passed one command return then echo as a second one. The pipe is not used for that
    – francois P
    Commented Dec 30, 2017 at 10:10


$ VARIABLE=$( pdftk file.pdf dump_data | grep NumberOfPages | awk '{print $2}' ) ; echo "$VARIABLE" 

The problem is to use a pipe (|) which doesn't work with echo.

  1. You don't need to pipe grep's output into awk. awk can do the same kind of regular expression pattern matching as grep (and a lot more).

  2. You need to double-quote variables when you use them. And command substitutions.

  3. As others have already pointed out, the pipe character doesn't terminate statements. Use a new line or ; instead.

Putting that all together:

VARIABLE="$(pdftk file.pdf dump_data | awk '/NumberOfPages/ {print $2}')"
echo "$VARIABLE"

BTW, pdfinfo from poppler-utils is another good tool for getting a summary of a PDF file's metadata (including the page count). It gives you just the file metadata (title, subject, author, keywords, page count, etc) in an easily-parsed format without details about each individual page (so it's noticeably faster on large PDF files).

VARIABLE="$(pdfinfo file.pdf| awk '/Pages/ {print $2}')"
echo "$VARIABLE"

You must log in to answer this question.

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