记录shell脚本的参数

AnC*_*AnC 41 unix linux shell

是否存在记录shell脚本参数的约定?

例如:

#!/usr/bin/env bash

# <description>
#
# Usage:
#  $ ./myScript param1 [param2]
# * param1: <description>
# * param2: <description>
Run Code Online (Sandbox Code Playgroud)

我不喜欢这个特定模板的一些事情:

  • 脚本的文件名(myScript)出现在文件本身中
  • 参数描述看起来很怪异
  • 之前的领先空间在$视觉上是有用的,但可能会导致语言与块注释混淆,导致一些验证工具抱怨混合/不一致的缩进(例如,此块中的空格,代码选项卡 - 当然,提供一个选项卡)

这有什么指导方针吗?

Cha*_*ens 39

传统上,您在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
Run Code Online (Sandbox Code Playgroud)


Edd*_*ddy 21

我通常将我的用法包装在函数中,所以我可以从-h param等中调用它.

#!/bin/bash
usage() {
    cat <<EOM
    Usage:
    $(basename $0) Explain options here

EOM
    exit 0
}

[ -z $1 ] && { usage; }
Run Code Online (Sandbox Code Playgroud)

  • 你需要引用`$ 1`因为它可以包含空格而```只是一个常规程序,它将`-z`作为第一个参数,```last.如果`$ 1`包含`"x -o 1 -eq 1"`,它将始终显示使用信息. (3认同)

leo*_*tzr 17

我会建议使用heredoc:

usage () {
    cat <<HELP_USAGE

    $0  [-a] -f <file>

   -a  All the instances.
   -f  File to write all the log lines
HELP_USAGE
}
Run Code Online (Sandbox Code Playgroud)

代替:

echo "$0  [-a] -f <file>"
echo
echo "-a  All the instances."
echo "-f  File to write all the log lines."
Run Code Online (Sandbox Code Playgroud)

我认为它比所有这些回声线更干净.


Joh*_*ood 11

执行此操作的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:  ---
#===============================================================================
Run Code Online (Sandbox Code Playgroud)

  • 呃,看起来像COBOL程序的识别部分.*不寒而栗*. (11认同)

rmm*_*mmh 5

我建议让你的脚本自动打印用法(如果它不应该在没有参数的情况下运行):

#!/usr/bin/env bash

if [ $# == 0 ]; then
    echo "Usage: $0 param1 [param2]"
    echo "* param1: <description>"
    echo "* param2: <description>"
fi
Run Code Online (Sandbox Code Playgroud)

  • 您可以使用 `$#` 作为参数计数的快捷方式。 (8认同)

Var*_*han 3

我宁愿写:

Usage: `basename $0` [option1]|[option2] param1
  Options:
   - option1:  .....
   - option2:  .....
  Parameters:
   - param1:   ..... 
Run Code Online (Sandbox Code Playgroud)

尝试查看标准 UNIX 实用程序的帮助格式(例如 ls --help)