15 August 2007

Viewing man pages as PDF

A coworker forwarded me a really simple script for converting man pages on my Mac into PDFs. It was based on this tip from Macworld.

There were a few minor problems though, in that this generated a PostScript file which Preview took some time to convert, and there was no kind of caching if you opened the same man page twice in a row.

This was easily fixed by using pstopdf to convert the PostScript to PDF before opening it in Preview and writing the PDF files into the system's temp directory in a standard format.

Add the following to your ~/.bash_profile to create the command:

pman()
{
    PMANFILE="/tmp/pman-${1}.pdf"
    if [ ! -e $PMANFILE ]; then   # only create if it doesn't already exist
        man -t "${1}" | pstopdf -i -o "$PMANFILE"
    fi
    if [ -e $PMANFILE ]; then     # in case create failed
        open -a /Applications/Preview.app/ "$PMANFILE"
    fi
}

You can then run pman bash to quickly get a 60-page PDF with the entire bash documentation. Nice! (This is a function rather than an alias because aliases can't take arguments in bash — see the bash documentation.)

I found this so useful and much easier to read than the console, that I made it my default man behaviour by aliasing the default command:

alias man=pman

Now, running man diff works really nicely. It generates a PDF which is cached, and opens the PDF in Preview where it is easy to search and read.

My previous articles related to scripting and Unix are: