【问题标题】:How to get the agrument after the command using GETOPTS in BASH如何在 BASH 中使用 GETOPTS 获取命令后的参数
【发布时间】:2011-10-07 17:48:30
【问题描述】:

脚本使用示例

./myscript --p 1984 --n someName

#!/bin/bash

while getopts :npr opt 
do
   case $opt in
     n ) echo name= ???                ;;
     p ) echo port=  ???               ;;
     r ) echo robot= "Something"       ;;
     ? ) echo  "Useage: -p [#]"        ;;
  esac
done

如何访问命令选项后面的参数?

此外,如果我输入:./myscript --p 1985 我想知道如何回显 1985 并使用该参数。

【问题讨论】:

  • 当然,你实际上调用命令为myscript -p 1984 -n someName

标签: bash getopts


【解决方案1】:

In bash, see help getopts: "When an option requires an argument, getopts places that argument into the shell variable OPTARG."

usage() { echo "Usage: $(basename $0) -n name -p port -r"; exit; }

while getopts :n:p:r opt   # don't forget the colons for opts that take an arg
do
   case $opt in
     n ) name="$OPTARG" ;;
     p ) port="$OPTARG" ;;
     r ) robot=chicken  ;;
     ? ) usage ;;
  esac
done
shift $(( OPTIND - 1 ))

echo "the name is $name"
echo "the port is $port"

我相信您可以在 google 上搜索解析 bash 中的选项的解决方案。这是几分钟的努力:

#!/bin/bash

usage() { echo foo; exit; }

while [[ $1 == -* ]]; do
  case "$1" in 
    --) shift 1; break ;;
    -p|--p|--port) port="$2"; shift 2;;
    -n|--n|--name) name="$2"; shift 2;;
    *) echo "unknown option: $1"; usage;;
  esac
done

echo "the name is $name"
echo "the port is $port"
echo "the rest of the args are:"; ( IFS=,; echo "$*" )

还有一个测试,

$ bash longopts.sh --port 1234 --bar a b c
unknown option: --bar
foo
$ bash longopts.sh --port 1234 a b c
the name is
the port is 1234
the rest of the args are:
a,b,c

【讨论】:

  • 移位 $(( OPTIND - 1 )) 有什么作用?
  • 这允许您从位置参数中删除刚刚处理的选项,以便您可以从命令行访问任何其他参数。
  • 注意,使用 getopts,您不能使用双破折号 (--p 1984)。您必须使用单个破折号 (-p 1984)
  • 那么可以 --port 吗?使用getopts?无论如何提供一个长命令并使用 -- 前缀也
  • 您不能将 getopts 用于长样式选项。答案已更新