Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a man page exists?

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?

like image 997
procleaf Avatar asked Feb 20 '23 07:02

procleaf


2 Answers

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
like image 83
Todd A. Jacobs Avatar answered Feb 21 '23 21:02

Todd A. Jacobs


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.

like image 41
thb Avatar answered Feb 21 '23 20:02

thb