user331905
user331905

Reputation: 317

Getting bash getopts to do something

I am attempting to figure out how to use bash getopts to process command lines. I have the following code:

    while getopts "e:n:t:s:h" opt
        do

            echo $opt
        done

I invoke it with a bash command line like this:

. ./testopts.sh -e MyE -s sanctity

and nothing gets printed.

Please help

Upvotes: 0

Views: 204

Answers (3)

clt60
clt60

Reputation: 63892

Here is an template what i'm using for argument processing.

It is far from optimal (for example uses too much sed, instead of builtin bash regexes and so on) but you can use it for the start:

#!/bin/bash

#define your options here
OPT_STR=":hi:o:c"

#common functions
err() { 1>&2 echo "$0: Error: $@"; return 1; }
required_arg() { err "Option -$1 need argument"; }
checkarg() { [[ "$1" =~ ${optre:--} ]] && { required_arg "$2"; return 1; } || { echo "$1" ; return 0; } }
phelp() { err "Usage: $0" "$(sed 's/^://;s/\([a-zA-Z0-9]\)/ -&/g;s/:/ [arg] /g;s/  */ /g' <<< "$OPT_STR")"; return 1; }

do_work() {
    echo "Here should go your script for processing $1"
}

## MAIN
declare -A OPTION
optre=$(sed 's/://g;s/.*/-[&]/' <<<"$OPT_STR")
while getopts "$OPT_STR" opt;
do
    #change here i,o,c to your options
    case $opt in
    i) OPTION[$opt]=$(checkarg "$OPTARG" $opt) || exit 1;;
    o) OPTION[$opt]=$(checkarg "$OPTARG" $opt) || exit 1;;
    c) OPTION[$opt]=1;;
    h) phelp || exit 1;;
    :) required_arg "$OPTARG" || exit 1 ;;
    \?) err "Invalid option: -$OPTARG" || exit 1;;
    esac
done

shift $((OPTIND-1))
#change here your options...
echo "iarg: ${OPTION[i]:-undefined}"
echo "oarg: ${OPTION[o]:-undefined}"
echo "carg: ${OPTION[c]:-0}"
echo "remainder args: =$@="

for arg in "$@"
do
    do_work "$arg"
done

Upvotes: 1

c-is-best
c-is-best

Reputation: 146

OPTIND=1
while getopts "e:n:t:s:h" opt
do
    case $opt in
        e) echo "e OPTARG=${OPTARG} ";;
        n) echo "n OPTARG=${OPTARG} ";;
        t) echo "t OPTARG=${OPTARG} ";;
        s) echo "s OPTARG=${OPTARG} ";;
        h) echo "h OPTARG=${OPTARG} ";;
    esac
done

Upvotes: -1

anubhava
anubhava

Reputation: 784998

$opt will only print switches e or s for you but to print passed argument you need to echo $OPTARG as well.

Like this script:

while getopts "e:n:t:s:h" opt
do
   echo $opt $OPTARG
done

Upvotes: 2

Related Questions