1

I am trying to write a ksh script that takes an optional flag and two mandatory strings as argument. The flag is denoted as -a. Thus the command look like one of the following when correct:

  1. command.sh -a -b abc -c 123
  2. command.sh -b xyz -c 789

I am using the following code in my script:

while getopts "a:b:c:" args
do
    case $args in

        a) # Flag
            flag=1
            ;;
        b) # str1
            str1=$OPTARG
            ;;
        c) # str2
            str2=$OPTARG
            ;;
        *) # usage
            echo "- - - - "
            exit 0
            ;;
    esac
done

if [[ -z $str1 || -z $str2 ]]
then
    echo "Incomplete arguments supplied\n"
    exit 1
fi

...

Doing so when I execute 1 (see above) it throws me the message Incomplete arguments supplied where as 2 (see above) is working fine.

Can anyone point out what is going wrong and recommend a rectification?

Thanks...

jww
  • 97,681
  • 90
  • 411
  • 885
Anirban
  • 550
  • 3
  • 19

2 Answers2

1

A colon (:) after the option letter specifies that the option (aka flag) requires an argument; since you have a colon (:) after the 'a', getopts is expecting an argument to go along with -a; try this instead:

while getopts "ab:c:" args
markp-fuso
  • 28,790
  • 4
  • 16
  • 36
  • Thanks! This worked... I think doing the following also be the same: `while getopts "b:c:a" args` (i.e, putting flag that needs no arguments at the end without a succeeding `:` to make it look more clean). – Anirban Jul 18 '17 at 06:37
0

-z option to check whether variable is set is not used correctly. Refer to the below link for correct usage: How to check if a variable is set in Bash?

Kaushik Nayak
  • 30,772
  • 5
  • 32
  • 45