Error handling for "no manual entry" in bash scripting

Viewed 40

I just started learning bash scripting and I've been trying to create a script that'd print every man page to a pdf file. Problem is I don't know how to handle errors for 'no manual entry found' and the script just creates a blank file for commands that have no manual entry.

#! /bin/bash

declare -a commands

commands=(pwd cd ls mkdir rmdir echo)

for i in "${commands[@]}"
do
    man $i | pandoc --pdf-engine=pdfroff -o $i.pdf
done

Thanks in advance and I am sorry if it was a stupid question.

1 Answers

From man man:

EXIT STATUS
       0      Successful program execution.
       ...
       16     At least one of the pages/files/keywords didn't exist or wasn't matched.

Check man exit status. if is the compound command that checks commands exit status. Assignment preserves exit status, you can assign and check at the same time.

if tmp=$(man "$i"); then
     <<<"$tmp" pandoc ....
else
     echo "Och nuuuu, there is no man page for $i" >&2
fi

Check your scripts with shellcheck.

Related