5

I'm trying to write a script to convert man pages to PDF files. The script I have right now is:

#! /usr/bin/env bash
[[ $# -ne 1 ]] && { echo "Usage: $(basename $0) [command]" ; exit 1 ; }
man -t ${1} | ps2pdf14 - > "${1}_man.pdf"

The problem is that if a man page does not exist, the script will still carry on executing, generating an empty PDF file. So I wonder if there's a way to determine if a man page exists?

Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
procleaf
  • 738
  • 3
  • 12

2 Answers2

7

Use Man's Exit Status from a Function

The man(1) manual page defines the following exit status codes:

EXIT STATUS

0      Successful program execution.
1      Usage, syntax or configuration file error.
2      Operational error.
3      A child process returned a non-zero exit status.
16     At least one of the pages/files/keywords didn't exist or wasn't
       matched.

That means you can use the exit status of man itself to determine if a page is available via manpath. For example:

check_for_man_page () {
    man "$1" > /dev/null 2>&1
}

With this function, you can use test conditionals on the exit status like so:

$ check_for_man_page "cat" && echo 'Found it!'
Found it!

$ check_for_man_page "quux" || echo 'Not found!'
Not found!

Using an If/Else Statement

Here's another way to do this, using an if/else statement to determine whether to run your original code:

if man "$1" > /dev/null 2>&1
then
    man -t ${1} | ps2pdf14 - > "${1}_man.pdf"
else
    echo "Missing man page: $1" >&2
fi
Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
  • 1
    For what it's worth, those specific exit status values may not apply on all platforms. My system returns exit status 1 for a missing man page. – Michael Hoffman Sep 03 '12 at 04:03
  • @MichaelHoffman Doesn't matter. As long as it exits with a non-zero exit status, you know *something* went wrong. If *what* went wrong matters, then you can create a case statement or just report the exit status directly with **$?** instead. – Todd A. Jacobs Sep 03 '12 at 04:08
  • It doesn't matter for this use case. – Michael Hoffman Sep 03 '12 at 04:59
  • @CodeGnome Didn't know bash function will return last command's exit status. Thanks for the function. – procleaf Sep 03 '12 at 05:16
3

It's not neat, but this seems to do what you want:

if man -w ${1} >/dev/null 2>/dev/null ; then
    man -t ${1} | ps2pdf14 - > "${1}_man.pdf"
fi

However, some man pages may exist in different sections of the manual -- for example man 1 printf and man 3 printf. You may wish to modify your script to take this into account.

thb
  • 13,796
  • 3
  • 40
  • 68