如何将getopt与这几个值一起使用? [英] How to use getopt with this several values?

查看:55
本文介绍了如何将getopt与这几个值一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试实现具有多个选项的脚本.我从 doc 开始,出现了一些错误,然后转到了浏览器.阅读一些链接并在SO上找到它:

I try to achieve a script with multi options. I started with the doc, get some errors, went to the browser. Read some links and find this on SO : Using getopts in bash shell script to get long and short command line options.

因此,我阅读并重写了我的脚本.我在某个地方犯了一个错误.我在哪里错了?

So I read it and rewrote my script. I made a mistake somewhere. Where am I wrong ?

SH

#!/bin/sh

TEMP=`getopt -o vfts: --long verbose,format,type,style: \
             -n 'opt2' -- "$@"`

if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi

eval set -- "$TEMP"

VERBOSE=false
FORMAT=
TYPE=
STYLE=
while true; do
    case "$1" in
        -v | --verbose ) VERBOSE=true; shift ;;
        -f | --format ) FORMAT="$2"; shift 2 ;;
        -t | --type ) TYPE="$2"; shift 2 ;;
        -s | --style ) STYLE="$2"; shift 2 ;;
        -- ) shift; break ;;
        -*) break ;;
        * ) break ;;
    esac
done

echo "verbose = $VERBOSE"
echo "format = $FORMAT"
echo "type = $TYPE"
echo "style = $STYLE"

输出

> ./opt2.sh -v -f fofo -t toto -s soso

verbose = true // ok
format = -t // should be fofo
type =  // should be toto
style = soso // ok

推荐答案

您的选项字符串错误,应为 vf:t:s:.冒号表示必需的参数,除了v之外,每个选项都有.还需要相应地调整长选项字符串.

Your options string is wrong, it should be vf:t:s:. The colon indicates a required argument which each of your options except for v has. Also need to adjust your long options string accordingly.

这篇关于如何将getopt与这几个值一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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