Bash Shell脚本嵌入文档

Bash Shell脚本嵌入文档,你想用一种简单方法为脚本提供格式化过的终端用户文档(如手册页或 HTML 页面)。你希望能将代码和文档标记放在同一个文件中,以此简化更新、分发以及版本控制。

解决方案

使用内建命令 :(空命令)和 here-document 在脚本中嵌入文档。

#!/usr/bin/env bash
# 实例文件:embedded_documentation

echo 'Shell script code goes here'

# 使用:和here-document嵌入文档
: <<'END_OF_DOCS'

Embedded documentation such as Perl's Plain Old Documentation (POD),
or even plain text here.

Any accurate documentation is better than none at all.

Sample documentation in Perl's Plain Old Documentation (POD) format adapted from
CODE/ch07/Ch07.001_Best_Ex7.1 and 7.2 in the Perl Best Practices example tarball
"PBP_code.tar.gz".

=head1 NAME

MY~PROGRAM--One-line description here

=head1 SYNOPSIS

  MY~PROGRAM [OPTIONS] <file>

=head1 OPTIONS

  -h = This usage.
  -v = Be verbose.
  -V = Show version, copyright, and license information.

=head1 DESCRIPTION

A full description of the application and its features.
May include numerous subsections (i.e., =head2, =head3, etc.)

[...]

=head1 LICENSE AND COPYRIGHT

=cut

END_OF_DOCS

然后用下列命令提取并使用 POD 文档。

# 自动分页,以便在屏幕上阅读
$ perldoc myscript

# 只提取usage小节
$ pod2usage myscript

# 创建HTML版
$ pod2html myscript > myscript.html

# 创建手册页
$ pod2man myscript > myscript.1

讨论

任何纯文本文档或标记都可以像这样使用,要么散布在脚本内,要么集中放在脚本末尾,后一种做法会更好些。考虑到安装了 bash 的计算机系统可能也安装了 Perl,POD 格式也许是不错的选择。Perl 通常包含 pod2* 程序,可用于将 POD 转换成 HTML、LaTeX、手册页、文本以及用法文件。

Damian Conway 所著的 Perl Best Practices(O’Reilly 出版)一书中有一些优秀的库模块和应用程序文档模板,可以轻松地转换包括纯文本在内的任何文档格式。

要想将所有的嵌入式文档放在脚本最后,还可以在文档起始位置前加上 exit 0。这样就会直接退出脚本,不再强制 shell 解析每一行代码来查找 here-document 的结尾,运行速度会快一点。不过你得小心,别覆盖了上一个运行失败的命令的退出码,因此可以考虑使用 set -e。如果你的脚本中散布着代码和嵌入式文档,那就别这样做了。

酷客网相关文章:

赞(0)

评论 抢沙发

评论前必须登录!