Clo*_*oud 13 python documentation bash shell scripting
例如,Python 脚本可以通过docstrings. 它的巧妙之处在于,它们可以在每个函数级别、每个方法级别、每个类级别进行定义,最重要的是(在我的问题的上下文中):每个文件级别。例如,文件的顶部可能如下所示:
#!/usr/bin/env python
"""
@brief  A script that does cool stuff.
"""
这样做的bash脚本支持这样的功能?即是否有一种“标准化”的方法来生成文件级文档集(即脚本目的、usage语法等的人类可读描述;以便另一个脚本很容易自动解析/提取这些信息?我的目标是创建几个自我记录的调试脚本,如果已经有标准/事实上的最佳方法来做到这一点,我想避免重新发明轮子。
您可以轻松地为 Bash 执行此操作,如果您需要确保与仅 POSIX shell(如 /bin/sh)或主要是 busybox 系统(如 Alpine)的兼容性,那就有点棘手了。
Linux 文档项目有一些很好的例子。
http://tldp.org/LDP/abs/html/here-docs.html
这个巧妙技巧的另一个转变使得“自记录”脚本成为可能。
例19-12。自记录脚本
Run Code Online (Sandbox Code Playgroud)#!/bin/bash # self-document.sh: self-documenting script # Modification of "colm.sh". DOC_REQUEST=70 if [ "$1" = "-h" -o "$1" = "--help" ] # Request help. then echo; echo "Usage: $0 [directory-name]"; echo sed --silent -e '/DOCUMENTATIONXX$/,/^DOCUMENTATIONXX$/p' "$0" | sed -e '/DOCUMENTATIONXX$/d'; exit $DOC_REQUEST; fi : <<DOCUMENTATIONXX List the statistics of a specified directory in tabular format. --------------------------------------------------------------- The command-line parameter gives the directory to be listed. If no directory specified or directory specified cannot be read, then list the current working directory. DOCUMENTATIONXX if [ -z "$1" -o ! -r "$1" ] then directory=. else directory="$1" fi echo "Listing of "$directory":"; echo (printf "PERMISSIONS LINKS OWNER GROUP SIZE MONTH DAY HH:MM PROG-NAME\n" \ ; ls -l "$directory" | sed 1d) | column -t exit 0使用 cat 脚本是实现此目的的另一种方法。
Run Code Online (Sandbox Code Playgroud)DOC_REQUEST=70 if [ "$1" = "-h" -o "$1" = "--help" ] # Request help. then # Use a "cat script" . . . cat <<DOCUMENTATIONXX List the statistics of a specified directory in tabular format. --------------------------------------------------------------- The command-line parameter gives the directory to be listed. If no directory specified or directory specified cannot be read, then list the current working directory. DOCUMENTATIONXX exit $DOC_REQUEST fi
一个稍微优雅的示例,使用函数来处理文档和错误消息。
#!/bin/sh
usage() {
cat << EOF
Usage: 
  $0 [-u [username]] [-p]
  Options:
    -u <username> : Optionally specify the new username to set password for.  
    -p : Prompt for a new password.
EOF
}
die() {
  echo
  echo "$1, so giving up.  Sorry."
  echo
  exit 2
}
if [ -z "$USER" ] ; then
  die "Could not identify the existing user"
fi
if $PSET ; then
  passwd $USER || die "Busybox didn't like your password"
fi
https://github.com/jyellick/mficli/blob/master/util/changecreds.sh