How do I check if a man page exists?
Asked Answered
A

2

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?

Antiphony answered 3/9, 2012 at 3:38 Comment(1)
Why not use troff/groff directly?Gobetween
M
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
Monstrance answered 3/9, 2012 at 3:55 Comment(4)
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.Usance
@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.Monstrance
It doesn't matter for this use case.Usance
@CodeGnome Didn't know bash function will return last command's exit status. Thanks for the function.Antiphony
H
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.

Halidom answered 3/9, 2012 at 3:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.