Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash getopts multiple arguments or default value

So I have a question about get opts in bash. I want to get the value of the arguments if they are present but if they are not present to use a default value. So the script should take a directory and an integer but if they aren't specified then $PWD and 3 should be default values. Here is what

while getopts "hd:l:" opt; do
    case $opt in
        d ) directory=$OPTARG;;
        l ) depth=$OPTARG;;
        h ) usage
        exit 0;;
        \? ) usage
        exit 1;;
    esac
like image 618
Greg Avatar asked Feb 27 '14 03:02

Greg


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.

What does getopts mean in Bash?

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. How it works. Specifying the optstring. Verbose error checking.

What is Optind in getopts?

According to man getopts , OPTIND is the index of the next argument to be processed (starting index is 1).

What does colon mean in getopts?

optstring must contain the option letters the command using getopts recognizes. If a letter is followed by a colon, the option is expected to have an argument, or group of arguments, which must be separated from it by white space.


1 Answers

You can just provide default value before while loop:

directory=mydir
depth=123
while getopts "hd:l:" opt; do
    case $opt in
        d ) directory=$OPTARG;;
        l ) depth=$OPTARG;;
        h ) usage
        exit 0;;
        *) usage
        exit 1;;
    esac
done
echo "<$directory> <$depth>"
like image 183
anubhava Avatar answered Sep 25 '22 03:09

anubhava