如何将getopts的第一个参数与其余参数分离?

4
#!/bin/bash

priority=false
it=0
dir=/

while getopts  "p:i" option
do
  case $option in
         i) it=$OPTARG;;
         p) priority=true;;
   esac
done

if [[ ${@:$OPTIND} != "" ]]
then
    dir=${@:$OPTIND}
fi
echo $priority $it $dir

如果我执行它,对于$dir,我会得到2 testDir,而对于$it,我会得到0,而不是期望的只有testDir2。如何获得期望的结果?

./test.sh -pi 2 testDir
true 0 2 testDir

如果你使用 -p 2 -i testDir,你会得到想要的行为吗? - sdolgy
https://dev59.com/AXVC5IYBdhLWcg3ww0Hr - Eric Fortis
运行 bash -x ./test.sh 以查看脚本正在做什么。if 块看起来非常奇怪:它的意思是如果有一个非空的非选项参数,那么将 dir 设置为对非选项参数执行路径名扩展和单词拆分的结果,并用空格连接它们。(很复杂,是吧?)我怀疑你的意思是 if [[ ${!OPTIND} != "" ]]; then dir=${!OPTIND}; fi。通常的方法甚至更简单:在解析选项后运行 shift $OPTIND,这样非选项参数就是 $1$2 等,因此 if [[ -n $1 ]]; then dir=$1; fi - Gilles 'SO- stop being evil'
2个回答

2
我会这样写:

我会写成这样:

#!/bin/bash

priority=false
it=0

while getopts ":hpi:" opt; do
    case "$opt" in
        h) echo "usage: $0 ...."; exit 0 ;;
        p) priority=true ;;
        i) it="$OPTARG" ;;
        *) echo "error: invalid option -$OPTARG"; exit 1 ;;
    esac
done

shift $(( OPTIND - 1 ))

dir="${1:-/}"

echo "priority=$priority"
echo "it=$it"
echo "dir=$dir"

1

你似乎将 getopts 的 optstring 参数写错了。你写成了 p:i,而你想要的是 pi:,这样 -i 开关才能带参数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接