是否存在记录shell脚本参数的约定?
例如:
#!/usr/bin/env bash
# <description>
#
# Usage:
# $ ./myScript param1 [param2]
# * param1: <description>
# * param2: <description>
我不喜欢这个特定模板的一些事情:
myScript
)出现在文件本身$
之前的前导空格在视觉上很有用,但可能会导致语句与块注释混淆,导致一些验证工具抱怨混合/不一致缩进(例如此块中的空格,代码选项卡 - 提供当然,人们更喜欢标签)对此有任何指导意见吗?
答案 0 :(得分:33)
传统上,您在usage()函数中记录您的参数:
#!/bin/bash
programname=$0
function usage {
echo "usage: $programname [-abch] [-f infile] [-o outfile]"
echo " -a turn on feature a"
echo " -b turn on feature b"
echo " -c turn on feature c"
echo " -h display help"
echo " -f infile specify input file infile"
echo " -o outfile specify output file outfile"
exit 1
}
usage
答案 1 :(得分:17)
我通常将我的用法包装在函数中,所以我可以从-h param等中调用它。
#!/bin/bash
usage() {
cat <<EOM
Usage:
$(basename $0) Explain options here
EOM
exit 0
}
[ -z $1 ] && { usage; }
答案 2 :(得分:12)
我会建议使用heredoc:
usage () {
cat <<HELP_USAGE
$0 [-a] -f <file>
-a All the instances.
-f File to write all the log lines
HELP_USAGE
}
而不是:
echo "$0 [-a] -f <file>"
echo
echo "-a All the instances."
echo "-f File to write all the log lines."
我认为它比所有这些 echo 行更清晰。
答案 3 :(得分:10)
执行此操作的Vim bash IDE:
#!/bin/bash
#===============================================================================
#
# FILE: test.sh
#
# USAGE: ./test.sh
#
# DESCRIPTION:
#
# OPTIONS: ---
# REQUIREMENTS: ---
# BUGS: ---
# NOTES: ---
# AUTHOR: Joe Brockmeier, jzb@zonker.net
# COMPANY: Dissociated Press
# VERSION: 1.0
# CREATED: 05/25/2007 10:31:01 PM MDT
# REVISION: ---
#===============================================================================
答案 4 :(得分:3)
我宁愿写:
Usage: `basename $0` [option1]|[option2] param1
Options:
- option1: .....
- option2: .....
Parameters:
- param1: .....
尝试查看标准UNIX实用程序格式化帮助的方式(例如ls --help)
答案 5 :(得分:2)
我建议让你的脚本自动打印用法(如果它不应该没有参数运行):
#!/usr/bin/env bash
if [ ${#@} == 0 ]; then
echo "Usage: $0 param1 [param2]"
echo "* param1: <description>"
echo "* param2: <description>"
fi