如何以支持在bash同时兼具短期和长期的选项? [英] How to support both short and long options at the same time in bash?

查看:114
本文介绍了如何以支持在bash同时兼具短期和长期的选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要支持庆典脚本短期和长期的选项,因此可以:

I want to support both short and long options in bash scripts, so one can:

$ foo -ax --long-key val -b -y SOME FILE NAMES

这可能吗?

推荐答案

getopt的支持长选项。

<一个href=\"http://linux.about.com/library/cmd/blcmdl1_getopt.htm\">http://linux.about.com/library/cmd/blcmdl1_getopt.htm

下面:

#!/bin/bash

OPTS=`getopt -o axby -l long-key: -- "$@"`
if [ $? != 0 ]
then
    exit 1
fi

eval set -- "$OPTS"

while true ; do
    case "$1" in
        -a) echo "Got a"; shift;;
        -b) echo "Got b"; shift;;
        -x) echo "Got x"; shift;;
        -y) echo "Got y"; shift;;
        --long-key) echo "Got long-key, arg: $2"; shift 2;;
        --) shift; break;;
    esac
done
echo "Args:"
for arg
do
    echo $arg
done

$ foo的-ax --long键val的输出-b -y某些文件名

Got a
Got x
Got long-key, arg: val
Got b
Got y
Args:
SOME
FILE
NAMES

这篇关于如何以支持在bash同时兼具短期和长期的选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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