linux - 如何检查手册页是否存在?

标签 linux bash conditional-statements manual

我正在尝试编写一个脚本来将手册页转换为 PDF 文件。我现在的脚本是:

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

问题是,如果手册页不存在,脚本仍会继续执行,生成一个空的 PDF 文件。所以我想知道是否有一种方法可以确定手册页是否存在?

最佳答案

使用函数的 Man 退出状态

man(1) 手册页定义了以下退出状态代码:

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.

这意味着您可以使用 man 本身的退出状态来确定页面是否可以通过 manpath 访问。例如:

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

有了这个函数,你可以像这样在退出状态上使用测试条件:

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

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

使用 If/Else 语句

这是执行此操作的另一种方法,使用 if/else 语句来确定是否运行您的原始代码:

if man "$1" > /dev/null 2>&1
then
    man -t ${1} | ps2pdf14 - > "${1}_man.pdf"
else
    echo "Missing man page: $1" >&2
fi

关于linux - 如何检查手册页是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12241709/

相关文章:

c++ - 在 Linux 中使用 C/C++ 强制 tcp/ip 跟踪路由经过特定跃点

linux - 在 :0 instead of :1 上启动 vncserver

python - 如何展平 Pandascore E-Sports GET 响应格式的 JSON 数据,以便在 pandas 中拥有非常干净的数据框?

java - 从 BASH 脚本检查 Java 版本的正确方法

c - 有条件地添加数字

linux - 是否可以从非 linux 系统远程调试 linux 代码?

linux - 这是 cron 作业的正确格式吗?

python - 是否可以执行 bash 脚本来下载 `pip install my-package` 上的非 python 依赖项

php - 比较日期 ("Y-m-d h:i:s");

python - 年金公式的 future 值(value)不起作用