Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

Bash : Parse options after arguments with getopts

In a script which request some arguments (arg) and options (-a), I would like to let the script user the possibility to place the options where he wants in the command line.

Here is my code :

while getopts "a" opt; do
  echo "$opt"
done
shift $((OPTIND-1))

echo "all_end : $*"

With this order, I have the expected behaviour :

./test.sh -a arg
a
all_end : arg

I would like to get the same result with this order :

./test.sh arg -a
all_end : arg -a
question from:https://stackoverflow.com/questions/65886127/bash-parse-options-after-arguments-with-getopts

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The getopt command (part of the util-linux package and different from getopts) will do what you want. The bash faq has some opinions about using that, but honestly these days most systems will have the modern version of getopt.

Consider the following example:

#!/bin/sh

options=$(getopt -o o: --long option: -- "$@")
eval set -- "$options"

while :; do
    case "$1" in
        -o|--option)
            shift
            OPTION=$1
            ;;
        --)
            shift
            break
            ;;
    esac

    shift
done

echo "got option: $OPTION"
echo "remaining args are: $@"

We can call this like this:

$ ./options.sh -o foo arg1 arg2
got option: foo
remaining args are: arg1 arg2

Or like this:

$ ./options.sh  arg1 arg2 -o foo
got option: foo
remaining args are: arg1 arg2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...