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?
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!
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With