How to support both short and long options at the same time in bash? [duplicate]

我怕爱的太早我们不能终老 提交于 2019-11-27 14:25:28

问题


This question already has an answer here:

  • Using getopts to process long and short command line options 32 answers

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

is it possible?


回答1:


getopt supports long options.

http://man7.org/linux/man-pages/man1/getopt.1.html

Here is an example using your arguments:

#!/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

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

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


来源:https://stackoverflow.com/questions/4180880/how-to-support-both-short-and-long-options-at-the-same-time-in-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!