是否可以将getopts与位置参数混合? [英] Is mixing getopts with positional parameters possible?

查看:110
本文介绍了是否可以将getopts与位置参数混合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设计一个shell脚本作为几个脚本的包装.我想使用getoptsmyshell.sh指定参数,并将其余参数以相同的顺序传递给指定的脚本.

I want to design a shell script as a wrapper for a couple of scripts. I would like to specify parameters for myshell.sh using getopts and pass the remaining parameters in the same order to the script specified.

如果按以下方式执行myshell.sh:

myshell.sh -h hostname -s test.sh -d waittime param1 param2 param3

myshell.sh param1 param2 -h hostname param3 -d waittime -s test.sh

myshell.sh param1 -h hostname -d waittime -s test.sh param2 param3

以上所有内容均应以

test.sh param1 param2 param3

是否可以利用 myshell.sh 中的选项参数并将其余参数发布到基础脚本中?

推荐答案

很抱歉在旧线程上发表评论,但是我想为那些像我一样正在寻找如何执行此操作的人发帖...

Sorry for commenting on an old thread, but thought I'd post for those, like me who were searching on how to do this...

我想做一些类似于OP的事情,并且找到了我需要的相关信息

I wanted to do something similar to the OP, and I found the relevant information I required here and here

基本上,如果您想执行以下操作:

Essentially if you want to do something like:

script.sh [options] ARG1 ARG2

然后获得如下所示的选择:

Then get your options like this:

while getopts "h:u:p:d:" flag; do
case "$flag" in
    h) HOSTNAME=$OPTARG;;
    u) USERNAME=$OPTARG;;
    p) PASSWORD=$OPTARG;;
    d) DATABASE=$OPTARG;;
esac
done

然后您可以像这样获取位置参数:

And then you can get your positional arguments like this:

ARG1=${@:$OPTIND:1}
ARG2=${@:$OPTIND+1:1}

更多信息和细节可通过上面的链接获得.

More information and details are available through the link above.

希望有帮助!

这篇关于是否可以将getopts与位置参数混合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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