0

I have been searching but i have a question in regards to bash scripting and getopts.

I am trying to build a fool proof script using getops. What would be the best approach so when the user using the option that it will throw an error if i add more than one.

Example:

script.sh -a > this will run options a

script.sh -aaaaa > an erro should throw something that says, only 1 flag is allowed.

Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • Set a flag when you see the option, unless the flag is already set in which case you throw the error. – rici Nov 27 '15 at 05:53
  • 1
    In general, Stackoverflow will be kinder to you if you show that you have made an effort. So, edit your answer and add your current code, working or not. – John1024 Nov 27 '15 at 05:55
  • sorry im new to the forum...will add code and check your script below John..thanks for looking. – robotcollector Nov 30 '15 at 20:31

1 Answers1

0

The code below uses getopts to parse options. When option a is seen, it sets variable a to have the value Yes. Before doing that, however, it checks to see if a already has a value. If it does, it prints an error.

#!/bin/sh
die () {
        echo "ERROR: $*. Aborting." >&2
        exit 1
}

a=
while getopts a arg ; do case $arg in
        a)
                [ "$a" ] && die "Option a already specified"
                a=Yes
                ;;
        :)      die "${0##*/}: Must supply an argument to $OPTARG." ;;
        \?)     die "Invalid option. Abort" ;;
        esac
done
shift $(($OPTIND - 1))

echo "Doing something useful now..."

The key part of the code is:

[ "$a" ] && die "Option a already specified"

The construct [ "$a" ] tests the value of $a. If it is non-empty, then the test returns true and this triggers the && operator to run the die command. If it is empty, then [ "$a" ] returns false and the die command is not run.

die is a function: it prints a message and exits with error code 1.

John1024
  • 109,961
  • 14
  • 137
  • 171