Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parse arguments after getopts

I want to call a bash script like this

$ ./scriptName -o -p -t something path/to/file 

This is as far as I get

#!/bin/bash  o=false p=false  while getopts ":opt:" options do     case $options in         o ) opt1=true         ;;         p ) opt2=true         ;;         t ) opt3=$OPTARG         ;;     esac done 

but how do I get the path/to/file?

like image 725
speendo Avatar asked Feb 27 '12 21:02

speendo


People also ask

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.

What does colon mean in getopts?

An option character in this string can be followed by a colon (' : ') to indicate that it takes a required argument. If an option character is followed by two colons (' :: '), its argument is optional; this is a GNU extension. getopt has three ways to deal with options that follow non-options argv elements.

What is Optind in getopts?

According to man getopts , OPTIND is the index of the next argument to be processed (starting index is 1). Hence, In sh foo.sh -abc CCC Blank arg1 is -abc , so after a we are still parsing arg1 when next is b ( a 1 ). Same is true when next is c , we are still in arg1 ( b 1 ).


2 Answers

You can do something like:

shift $(($OPTIND - 1)) first_arg=$1 second_arg=$2 

after the loop has run.

like image 154
Oliver Charlesworth Avatar answered Sep 18 '22 09:09

Oliver Charlesworth


To capture all the remaining parameters after the getopts processing, a good solution is to shift (remove) all the processed parameters (variable $OPTIND) and assign the remaining parameters ($@) to a specific variable. Short answer:

shift $(($OPTIND - 1)) remaining_args="$@" 

Long example:

#!/bin/bash  verbose=false  function usage () {     cat <<EOUSAGE $(basename $0) hvr:e:     show usage EOUSAGE }  while getopts :hvr:e: opt do     case $opt in         v)             verbose=true             ;;         e)             option_e="$OPTARG"             ;;         r)             option_r="$option_r $OPTARG"             ;;         h)             usage             exit 1             ;;         *)             echo "Invalid option: -$OPTARG" >&2             usage             exit 2             ;;     esac done   echo "Verbose is $verbose" echo "option_e is \"$option_e\"" echo "option_r is \"$option_r\"" echo "\$@ pre shift is \"$@\"" shift $((OPTIND - 1)) echo "\$@ post shift is \"$@\"" 

This will output

$ ./test-getopts.sh -r foo1 -v -e bla -r foo2 remain1 remain2 Verbose is true option_e is "bla" option_r is " foo1 foo2" $@ pre shift is "-r foo1 -v -e bla -r foo2 remain1 remain2" $@ post shift is "remain1 remain2" 
like image 32
Thomas B in BDX Avatar answered Sep 21 '22 09:09

Thomas B in BDX