如何在bash中结合使用getopts和position参数? [英] How to combine getopts and positional parameters in bash?

查看:55
本文介绍了如何在bash中结合使用getopts和position参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想同时使用 getopts 和位置参数,但是如果我将位置参数传递给程序,则 getopts 将会丢失.

I want to use both getopts and positional parameters, but if I pass in a positional parameter to the program the getopts get lost.

directory=$1

while getopts l: flag; do
  case "$flag" in
    l) level=$OPTARG;;
  esac
done

if [ -n "$level" ]; then
  echo "Level exist!"
else
  echo "Level doesn't exist!"
fi

所以当我像这样运行程序时:

So when I run the program like this:

sh myprogram.sh ~/documents -l 2

我希望:

级别存在!

相反,它返回:

级别不存在!

问题是,如果我运行的程序没有这样的位置参数(〜/documents):

The thing is, if I run the program without the positional parameter (~/documents) like this:

sh myprogram.sh -l 2

我得到正确的输出:

级别存在!

那是为什么?如何在bash中同时使用位置参数和 getopts ?

Why is that? How can I use both positional parameters and getopts in bash?

谢谢!

推荐答案

大多数工具都以以下形式编写: tool [options] arg ...

Most tools are written in the form: tool [options] arg ...

所以您可以这样做:

# first, parse the options:
while getopts l: flag; do
  case "$flag" in
    l) level=$OPTARG;;
    \?) exit 42;;
  esac
done

# and shift them away
shift $((OPTIND - 1))

# validation
if [ -n "$level" ]; then
  echo "Level exist!"
else
  echo "Level doesn't exist!"
fi

# THEN, access the positional params
echo "there are $# positional params remaining"
for ((i=1; i<=$#; i++)); do
  printf "%d\t%s\n" $i "${!i}"
done

如果用户提供未知选项或未能提供必需的参数,请使用 \?中止脚本

Use the \? to abort the script if the user provides an unknown option or fails to provide a required argument

并像这样调用它:

$ bash test.sh
Level doesn't exist!
there are 0 positional params remaining

$ bash test.sh -l 2
Level exist!
there are 0 positional params remaining

$ bash test.sh -l 2 foo bar
Level exist!
there are 2 positional params remaining
1   foo
2   bar

$ bash test.sh -x
test.sh: illegal option -- x

$ bash test.sh -l
test.sh: option requires an argument -- l

但是您不能将选项放在参数之后:getopts在找到第一个非选项参数时停止

But you cannot put the options after the arguments: getopts stops when the first non-option argument is found

$ bash test.sh foo bar -l 2
Level doesn't exist!
there are 4 positional params remaining
1   foo
2   bar
3   -l
4   2

这篇关于如何在bash中结合使用getopts和position参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆