Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 229
Xiè Jìléi Avatar asked Nov 15 '10 02:11

Xiè Jìléi


People also ask

Should I use getopt or getopts?

The main differences between getopts and getopt are as follows: getopt does not handle empty flag arguments well; getopts does. getopts is included in the Bourne shell and Bash; getopt needs to be installed separately. getopt allows for the parsing of long options ( --help instead of -h ); getopts does not.

How do you parse arguments in bash?

Parsing Short Command-Line Options With getopts. In Bash, we can use both short and long command-line options. The short option starts with the single hyphen (-) character followed by a single alphanumeric character, whereas the long option starts with the double hyphen (–) characters followed by multiple characters.

What is getopts in shell script?

Description. The getopts command is a Korn/POSIX Shell built-in command that retrieves options and option-arguments from a list of parameters. An option begins with a + (plus sign) or a - (minus sign) followed by a character. An option that does not begin with either a + or a - ends the OptionString.


1 Answers

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 
like image 67
Brian Clements Avatar answered Sep 18 '22 18:09

Brian Clements