iamnearlythere

Getopt in Bash

How to properly read command line arguments for a bash script and do it well even without getopt:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
while :; do
        case "$1" in
                -h|--help)
                        echo "This is helping"
                        exit 0
                        ;;

                -s|--simple-flag)
                        echo "You passed a flag"
                        shift
                        ;;
                -p|--pass-option)
                        shift
                        echo "You set option to $1"
                        option="$1"
                        shift
                        ;;
                -*)
                        echo "That's a weird option"
                        exit 1
                *)
                        # No more args to read
                        break
                        ;;
done

I think the syntax is much cleaner than that of getopt's as well -- that is, if you've even got a bash version supporting getopt.

Comments