1

脚本使用示例

./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我想知道 ot echo 1985 如何返回并使用该参数。

4

1 回答 1

4

在 bash 中,请参阅help getopts:“当一个选项需要一个参数时,getopts 将该参数放入 shell 变量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"

我敢肯定,您可以在 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
于 2011-10-07T18:13:56.307 回答