Márk Maros
Márk Maros

Reputation: 31

BASH getopts define what $OPTARG can be

usage ()
{
echo "USAGE MANUAL"
echo "-u -> displays this usage manual"
echo "-t -> sets EXEC variable to echo"
echo "-t -> sets DEPTH variable to inputed string" 
exit 1
}
while getopts ":t:u:d:" o; do
case "${o}" in
t)
    EXEC=echo
    ;;
d)  
    DEPTH=${OPTARG}
    ;;            
u)
    usage
    ;;
esac
done
shift $((OPTIND-1))

if [ -z "${d}" ] || [ -z "${t}" ]; then
usage
fi

If i get it right if i do this:

./script -d

I have to provide something like:

./script -d full

The question is, how do i restrict what the argument of d can be. Like if someone types ./script -d full or ./script -d empty its gonna change the value of DEPTH to full or empty, but if they put something like ./script -d infinite the script doesnt run and echo somthing like wrong argument provided.

Upvotes: 2

Views: 41

Answers (1)

choroba
choroba

Reputation: 241768

You can use a nested case:

d) case "$OPTARG" in
       full|empty) DEPTH=$OPTARG ;;
       *) echo 'Invalid depth' >&2 ; exit 1 ;;
   esac
   ;;

Upvotes: 4

Related Questions