如何使用getopt在UNIX中创建多字符参数?

21

我正在尝试制作一个getopt命令,使得当我将"-ab"参数传递给脚本时,该脚本将把-ab视为单个参数。

#!/bin/sh
args=`getopt "ab":fc:d $*`
set -- $args
for i in $args
do
case "$i" in
        -ab) shift;echo "You typed ab $1.";shift;;
        -c) shift;echo "You typed a c $1";shift;;
esac
done

然而,这似乎无效。有人可以提供帮助吗?

5个回答

17

getopt不支持您要查找的内容。您可以使用单个字母(-a)或长选项(--long)。像-ab这样的内容与-a b被视为相同:选项a和参数b。请注意,长选项前缀为两个破折号。


3
你能演示一下如何使用 --long 吗? - Philippe Fanaro

2
我曾经也遇到过这个问题,后来我开始学习getopt和getopts。
它们支持单字符选项和长选项。
我有一个类似的需求,需要多个输入参数。
所以,我想出了这个方法——在我的情况下它起作用了,希望能帮到你。
function show_help {
    echo "usage:  $BASH_SOURCE --input1 <input1> --input2 <input2> --input3 <input3>"
    echo "                     --input1 - is input 1 ."
    echo "                     --input2 - is input 2 ."
    echo "                     --input3 - is input 3 ."
}

# Read command line options
ARGUMENT_LIST=(
    "input1"
    "input2"
    "input3"
)



# read arguments
opts=$(getopt \
    --longoptions "$(printf "%s:," "${ARGUMENT_LIST[@]}")" \
    --name "$(basename "$0")" \
    --options "" \
    -- "$@"
)


echo $opts

eval set --$opts

while true; do
    case "$1" in
    h)
        show_help
        exit 0
        ;;
    --input1)  
        shift
        empId=$1
        ;;
    --input2)  
        shift
        fromDate=$1
        ;;
    --input3)  
        shift
        toDate=$1
        ;;
      --)
        shift
        break
        ;;
    esac
    shift
done

注意 - 我根据自己的需求添加了帮助功能,如果不需要可以将其删除。最初的回答:

请注意 - 根据我的需求,我已添加了帮助函数,如果不需要可以删除它。


2

虽然有些人这样做(例如java -cp classpath),但这不是Unix的方式。

技巧:不要使用-ab arg,而是使用-b arg和一个虚拟选项-a

这样,-ab arg就可以实现你想要的效果。(-b arg也可以;希望这不是一个错误,而是一种快捷方式特性...)

唯一的变化是你的那行代码:

-ab) shift;echo "You typed ab $1.";shift;;

变成

-b) shift;echo "You typed ab $1.";shift;;

1

GNU getopt 有 --alternative 选项

-a, --alternative
    Allow long options to start with a single '-'.

例子:

#!/usr/bin/env bash

SOPT='a:b'
LOPT='ab:'
OPTS=$(getopt -q -a \
    --options ${SOPT} \
    --longoptions ${LOPT} \
    --name "$(basename "$0")" \
    -- "$@"
)

if [[ $? > 0 ]]; then
    exit 2
fi

A= 
B=false
AB=

eval set -- $OPTS

while [[ $# > 0 ]]; do
    case ${1} in
        -a)  A=$2 && shift   ;;
        -b)  B=true          ;;
        --ab) AB=$2 && shift ;;
        --)                  ;;
        *)                   ;;
    esac
    shift
done

printf "Params:\n    A=%s\n    B=%s\n    AB=%s\n" "${A}" "${B}" "${AB}"

$ ./test.sh -a aaa -b -ab=test
Params:
    A=aaa
    B=true
    AB=test

-5

getopt支持长格式。您可以在SO上搜索示例。例如,请参见此处


5
请问您能否提供一个使用这个的例子? - Waffles

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接