Automator service: delete last page from PDF with use of pdfsplit via bash

automatorbashpdfterminal

I would like to design a simple Automator service that would delete last page from PDF passed via finder. My proposed syntax for the Shell Script is:

for f in "$@"
do
    pages=`pdfcount "$f"`
    pagescut=`$pages - 1`
    /usr/local/bin/pdfsplit "$f" - $pagescut > "$f".tmp
    rm "$f"
    mv "$f".tmp "$f"
done

My Automator workflow looks like that:
Automator screenshot
The syntax to delete first page: /usr/local/bin/pdfsplit "$f" 2- > "$f".tmp, works like a charm so the error must be with doing the arithmetic on page numbers. I tried to modify the syntax:

for f in "$@"
do
    pages=`pdfcount "$f"`
    pagescut=`$(( ${pages} - 1 ))`
    /usr/local/bin/pdfsplit "$f" - $pagescut > "$f".tmp
    rm "$f"
    mv "$f".tmp "$f"
done

but I'm not getting the desired results. How to construct this service properly?

Best Answer

You have a couple of errors on your syntax. Replace the following lines:

pages=`pdfcount "$f"`
pagescut=`$(( ${pages} - 1 ))`

With this ones:

pages=$(pdfcount "$f")
pagescut=$(($pages - 1))