在getopts之后使用shift $((OPTIND-1))的原因是什么? [英] What is a reason for using shift $((OPTIND-1)) after getopts?

查看:292
本文介绍了在getopts之后使用shift $((OPTIND-1))的原因是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到shift会将cli args数组向左移动,默认值为n.这意味着我可以使用while循环内的$ 1 shift将数组的值分配给现有变量.我不太了解的是为什么在下面的上下文中使用它.输入args已经分配了值,删除移位$((OPTIND-1))不会改变这一事实.来源: http://linux.die.net/man/3/optind

I realise that shift moves the array of cli args n space to the left, and the default of n is 1. This means I can assign the values the array to existing varibles using $1 shift inside a while loop. What I don't quite understand is why it is used in this context below. The input args have been assigned to values already and deleting shift $((OPTIND-1)) doesnt change this fact. Source: http://linux.die.net/man/3/optind

while getopts ":h:a:fc" opt; do
    case $opt in
        h)
            print_help
            exit 0
            ;;
        a)
            aaaa=${OPTARG}
            ;;
        f)
            force=1
            ;;
        c)
            CLEAN=1
            ;;
        \?)
            echoerr "Invalid option -$OPTARG"
            print_help
            exit 1
            ;;
    esac
done

shift $((OPTIND-1))

推荐答案

此移位从参数列表中删除了 getopts 循环处理的参数,以便脚本的其余部分可以处理其余部分命令行(如果有的话)中带有$ 1 ...的常规方式,而不用担心 getopts 处理的选项数量.

The shift removes the parameters processed by the getopts loop from the parameter list, so that the rest of the script can process the remainder of the command line (if any) with $1... in the usual manner, without concern for the number of options processed by getopts.

考虑使用情况的假想脚本

Consider a hypothetical script with the usage

frobble [-f] [-c] [-a hostname] filename ...

上面的 getopts 循环负责解析 -f -c -a ,如果它们存在,但不会将其从参数列表中删除.这意味着要获取文件名参数,您需要找出已处理了多少个选项,然后从那里继续进行处理.方便地, getopts 告诉您第一个未处理参数的索引:变量 OPTIND .

The getopts loop above takes care of parsing the -f,-c and -a, if they are present, but doesn't remove them from the argument list. Which means that to get at your filename argument, you need to find out how many options were processed, and continue processing from there. Conveniently, getopts tells you the index of the first unprocessed argument: the variable OPTIND.

您可以丢弃已处理的选项,而对其余的参数重新编号,以使文件名始终为 $ 1 .

And instead of messing with offsets and stuff, you can just discard the processed options, renumbering the rest of the arguments so your filename is always $1.

这就是 shift $((OPTIND-1))的作用.

这篇关于在getopts之后使用shift $((OPTIND-1))的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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