在 Bash 函数中使用 getopts [英] Using getopts inside a Bash function

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

问题描述

我想在我在 .bash_profile 中定义的函数中使用 getopts.这个想法是我想向这个函数传递一些标志来改变它的行为.

I'd like to use getopts inside a function that I have defined in my .bash_profile. The idea is I'd like to pass in some flags to this function to alter its behavior.

代码如下:

function t() {
    echo $*
    getopts "a:" OPTION
    echo $OPTION
    echo $OPTARG
}

当我这样调用它时:

t -a bc

我得到这个输出:

-a bc
?
 

怎么了?我想获得值 bc 而无需手动移动和解析.如何在函数内正确使用 getopts?

What's wrong? I'd like to get the value bc without manually shifting and parsing. How do I use getopts correctly inside a function?

更正了我的代码片段以尝试 $OPTARG,但无济于事

corrected my code snippet to try $OPTARG, to no avail

编辑#2:好的,结果证明代码没问题,我的外壳不知何故搞砸了.打开一个新窗口解决了它.arg 值确实在 $OPTARG 中.

EDIT #2: OK turns out the code is fine, my shell was somehow messed up. Opening a new window solved it. The arg value was indeed in $OPTARG.

推荐答案

正如@Ansgar 所指出的,您选项的参数存储在 ${OPTARG} 中,但这不是唯一的在函数内使用 getopts 时要注意.您还需要通过取消设置或声明 local 来确保 ${OPTIND} 对函数来说是本地的,否则在多次调用函数时会遇到意外行为次.

As @Ansgar points out, the argument to your option is stored in ${OPTARG}, but this is not the only thing to watch out for when using getopts inside a function. You also need to make sure that ${OPTIND} is local to the function by either unsetting it or declaring it local, otherwise you will encounter unexpected behaviour when invoking the function multiple times.

t.sh:

#!/bin/bash

foo()
{
    foo_usage() { echo "foo: [-a <arg>]" 1>&2; exit; }

    local OPTIND o a
    while getopts ":a:" o; do
        case "${o}" in
            a)
                a="${OPTARG}"
                ;;
            *)
                foo_usage
                ;;
        esac
    done
    shift $((OPTIND-1))

    echo "a: [${a}], non-option arguments: $*"
}

foo
foo -a bc bar quux
foo -x

示例运行:

$ ./t.sh
a: [], non-option arguments:
a: [bc], non-option arguments: bar quux
foo: [-a <arg>]

如果你注释掉#local OPTIND,你会得到:

If you comment out # local OPTIND, this is what you get instead:

$ ./t.sh
a: [], non-option arguments:
a: [bc], non-option arguments: bar quux
a: [bc], non-option arguments:

除此之外,其用法与在函数外使用时相同.

Other than that, its usage is the same as when used outside of a function.

这篇关于在 Bash 函数中使用 getopts的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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