LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   mandatory and optional arguments (https://www.linuxquestions.org/questions/linux-general-1/mandatory-and-optional-arguments-885433/)

nano2 06-09-2011 10:22 AM

mandatory and optional arguments
 
Hi ,
I am using getopts to take parse optional arguments but i also pass in mandatory arguments first
Code:

#!/bin/bash


print_usage()
{
    perror "$@"
}
arg1="$1"
arg2="$2"
shift 2
while getopts f:d: opt
do
  case $opt in
              f) file="${OPTARG}";;
              d) dir="${OPTARG}";;
              ?) print_usage $0
            exit 1;;
  esac
done
echo "Argument 1 = $arg1"
echo "Argument 2 = $arg2"
echo "File=$file"
echo "Dir=$dir"

./script arg1 arg2 -f file -d dir this works fine

But when i pass in the wrong number of mandatory arguments and pass in the optional argument the command line gets all messed up like so

./script arg1 -f BLAH -d DIR
Argument 1 = arg1
Argument 2 = -f
File=
Dir=

Any ideas how to stop this ???

acid_kewpie 06-09-2011 10:39 AM

Please post your thread in only one forum. Posting a single thread in the most relevant forum will make it easier for members to help you and will keep the discussion in one place. This thread is being closed because it is a duplicate.


All times are GMT -5. The time now is 05:35 AM.