Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why 'getopts' within a function fails to work?

Tags:

bash

ubuntu

function readArgs() {
    while getopts "i:o:p:s:l:m" OPTION; do
        case "$OPTION" in
            i)
                input="$OPTARG"
                ;;
            o)
                output="$OPTARG"
                ;;
            ...
        esac
    done
}

readArgs

if [[ -z "$input" ]]; then
    echo "Not set!"
fi

This is always giving me Not set! but if I comment out the lines function readArgs() {, } and readArgs, it works. Why?

Also,

input="$OPTARG"
echo "$input"
;;

does not work.

like image 571
Hindol Avatar asked May 04 '12 18:05

Hindol


People also ask

How does getopt work?

Normally, getopt is called in a loop. When getopt returns -1 , indicating no more options are present, the loop terminates. A switch statement is used to dispatch on the return value from getopt . In typical use, each case just sets a variable that is used later in the program.

What does Getopts mean in Bash?

Updated: 02/01/2021 by Computer Hope. On Unix-like operating systems, getopts is a builtin command of the Bash shell. It parses command options and arguments, such as those passed to a shell script.

Which of these is a difference between getopt and Getopts?

getopt vs 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.


2 Answers

getopts is parsing the arguments to the readArgs function, and you're not giving that function any arguments.

Try with:

readArgs "$@"
like image 84
Mat Avatar answered Sep 28 '22 15:09

Mat


getopts relies on the OPTIND variable being initialized to 1. Either do

readArgs() { OPTIND=1; ...

or

readArgs() { local OPTIND; ...
like image 43
glenn jackman Avatar answered Sep 28 '22 15:09

glenn jackman