在Bash中解析命令行参数的最佳方法?

Log*_*ion 11 bash command-line getopts

经过几天的研究,我仍然无法找到在.sh脚本中解析cmdline args的最佳方法.根据我的参考资料,getopts cmd是要走的路,因为它"在不干扰位置参数变量的情况下提取和检查开关.意外的开关或缺少参数的开关被识别并报告为错误. "

当涉及空格但是可以识别常规和长参数(-p和--longparam)时,位置参数(例如2 - $ @,$#等)显然不能正常工作.我注意到,当使用嵌套引号传递参数时,这两种方法都会失败("这是"引用""引号"".").这三个代码示例中哪一个最能说明处理cmdline args的方法?大师不推荐使用getopt函数,所以我试图避免它!

例1:

#!/bin/bash
for i in "$@"
do
case $i in
    -p=*|--prefix=*)
    PREFIX=`echo $i | sed 's/[-a-zA-Z0-9]*=//'`

    ;;
    -s=*|--searchpath=*)
    SEARCHPATH=`echo $i | sed 's/[-a-zA-Z0-9]*=//'`
    ;;
    -l=*|--lib=*)
    DIR=`echo $i | sed 's/[-a-zA-Z0-9]*=//'`
    ;;
    --default)
    DEFAULT=YES
    ;;
    *)
            # unknown option
    ;;
esac
done
exit 0
Run Code Online (Sandbox Code Playgroud)

例2:

#!/bin/bash
echo ‘number of arguments’
echo "\$#: $#"
echo ”

echo ‘using $num’
echo "\$0: $0"
if [ $# -ge 1 ];then echo "\$1: $1"; fi
if [ $# -ge 2 ];then echo "\$2: $2"; fi
if [ $# -ge 3 ];then echo "\$3: $3"; fi
if [ $# -ge 4 ];then echo "\$4: $4"; fi
if [ $# -ge 5 ];then echo "\$5: $5"; fi
echo ”

echo ‘using $@’
let i=1
for x in $@; do
echo "$i: $x"
let i=$i+1
done
echo ”

echo ‘using $*’
let i=1
for x in $*; do
echo "$i: $x"
let i=$i+1
done
echo ”

let i=1
echo ‘using shift’
while [ $# -gt 0 ]
do
echo "$i: $1"
let i=$i+1
shift
done

[/bash]

output:

bash> commandLineArguments.bash
number of arguments
$#: 0

using $num
$0: ./commandLineArguments.bash

using $@

using $*

using shift
#bash> commandLineArguments.bash  "abc def" g h i j*
Run Code Online (Sandbox Code Playgroud)

例3:

#!/bin/bash

while getopts ":a:" opt; do
  case $opt in
    a)
      echo "-a was triggered, Parameter: $OPTARG" >&2
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      exit 1
      ;;
  esac
done

exit 0
Run Code Online (Sandbox Code Playgroud)

Aus*_*ips 19

我发现使用getopt是最简单的.它提供了正确的参数处理,否则会很棘手.例如,getopt将知道如何处理命令行上指定的long选项的参数--arg=option--arg option.

解析传递给shell脚本的任何输入有用的是使用"$@"变量.有关它的不同之处,请参阅bash手册页$@.它确保您可以处理包含空格的参数.

这是一个如何编写s脚本来解析一些简单命令行参数的示例:

#!/bin/bash

args=$(getopt -l "searchpath:" -o "s:h" -- "$@")

eval set -- "$args"

while [ $# -ge 1 ]; do
        case "$1" in
                --)
                    # No more options left.
                    shift
                    break
                   ;;
                -s|--searchpath)
                        searchpath="$2"
                        shift
                        ;;
                -h)
                        echo "Display some help"
                        exit 0
                        ;;
        esac

        shift
done

echo "searchpath: $searchpath"
echo "remaining args: $*"
Run Code Online (Sandbox Code Playgroud)

并使用这样来表明空格和引号被保留:

user@machine:~/bin$ ./getopt_test --searchpath "File with spaces and \"quotes\"."
searchpath: File with spaces and "quotes".
remaining args: other args
Run Code Online (Sandbox Code Playgroud)

有关使用的一些基本信息getopt可以在这里找到

  • 这是getopt Austin的一个很好的例子.这个特定主题已在[stackoverflow]上进行了广泛讨论(http://stackoverflow.com/questions/402377/using-getopts-in-bash-shell-script-to-get-long-and-short-command-line-选项/ 7680682#7680682).不同之处在于,旧的getopt不如getopts强大,并且不适用于旧系统.只要有相同开关的短版本,Getopts就可以解析长开关,因此需要稍微调整一下.我会坚持w/getopts.我更倾向于使用内置函数而不是旧的exec(getopt)来使用专业脚本. (2认同)

Tet*_*Tet 9

如果你想避免使用,getopt你可以使用这个很好的快速方法:

  • 将所有选项的帮助定义为##注释(根据需要自定义)。
  • 为每个选项定义一个同名的函数。
  • 将此脚本的最后五行复制到您的脚本中(魔术)。

示例脚本: log.sh

#!/bin/sh
## $PROG 1.0 - Print logs [2017-10-01]
## Compatible with bash and dash/POSIX
## 
## Usage: $PROG [OPTION...] [COMMAND]...
## Options:
##   -i, --log-info         Set log level to info (default)
##   -q, --log-quiet        Set log level to quiet
##   -l, --log MESSAGE      Log a message
## Commands:
##   -h, --help             Displays this help and exists
##   -v, --version          Displays output version and exists
## Examples:
##   $PROG -i myscrip-simple.sh > myscript-full.sh
##   $PROG -r myscrip-full.sh   > myscript-simple.sh
PROG=${0##*/}
LOG=info
die() { echo $@ >&2; exit 2; }

log_info() {
  LOG=info
}
log_quiet() {
  LOG=quiet
}
log() {
  [ $LOG = info ] && echo "$1"; return 1 ## number of args used
}
help() {
  grep "^##" "$0" | sed -e "s/^...//" -e "s/\$PROG/$PROG/g"; exit 0
}
version() {
  help | head -1
}

[ $# = 0 ] && help
while [ $# -gt 0 ]; do
  CMD=$(grep -m 1 -Po "^## *$1, --\K[^= ]*|^##.* --\K${1#--}(?:[= ])" log.sh | sed -e "s/-/_/g")
  if [ -z "$CMD" ]; then echo "ERROR: Command '$1' not supported"; exit 1; fi
  shift; eval "$CMD" $@ || shift $? 2> /dev/null
done
Run Code Online (Sandbox Code Playgroud)

测试

运行此命令:

./log.sh --log yep --log-quiet -l nop -i -l yes
Run Code Online (Sandbox Code Playgroud)

产生这个输出:

yep
yes
Run Code Online (Sandbox Code Playgroud)

顺便说一句:它与兼容!

  • 非常有用的脚本,除了使用引号时无法正确生成参数之外,例如: `./log.sh --log "string inquotes"` 输出 `string`。你可能想改变这一行:`shift; 评估“$CMD”$@ || 转移$?2> /dev/null` 改为 `shift; $CMD“$@”|| 转移$?2> /dev/null` 为了正确的引用处理,更改似乎可以正常运行。 (4认同)
  • 上面 @R.StackUser 提到的“$@”中的另一个小外观改进与正确的引号处理相结合:``bash help() { grep "^##" "$0" | sed -e "s/^##.//" -e "s/^##$//" -e "s/\$PROG/$PROG/g"; 退出 ${0:-0} } ``` (2认同)