0

I am setting up a script in bash that return some information about a specific dictionary (french for example). I want that this script supports some parameters (4 currently). The issue is how manage the parameters easily than via many conditions ?

For the time being I am testing all the arguments of the script ($1, $2, ..) to be able to know which argument refers to which parameter

# langstat.sh : give statistics on letter occurrences in a specific language
# Usage : langstat.sh <dictionary>
# -> Display the number of times each letter is used at least once in a word of <dictionary>
# Usage : langstat.sh --percentage <dictionary>
# -> Display the percentage of times each letter is used at least once in a word of <dictionary>
# Usage : langstat.sh --word <word> <dictionary>
# -> Return true if <word> is a word of <dictionary>
# Usage : langstat.sh --all <dictionary>
# -> Display the number of times each letter is used in <dictionary>
# Usage : langstat.sh --alphabet <alphabet> <dictionary>
# -> Display the number of times each letter is used at least once in a word of <dictionary> using <alphabet> as alphabet


if [[ $# -lt 1 || $# -gt 5 ]]
then
    echo "Usage : $0 [--percentage] [--all] [--alphabet <alphabet>] <dictionary>"
    echo "Usage : $0 --word <word> <dictionary>"
    exit
fi


......
......
......

# Tests to understand how parameters are ordered
if [ $# -eq 1 ]
then

elif [ $# -eq 2 ]
then
    if [ $1 == "--percentage" ]
    then

    elif [ $1 == "--all" ]
    then

    fi
elif [ $# -eq 3 ]
then
    if [[ $1 == '--percentage' && $2 == '--all' || $1 == '--all' && $2 == '--percentage' ]]
    then

    elif [ $1 == '--alphabet' ]
    then

    elif [ $1 == '--word' ]
    then

    fi
elif [ $# -eq 4 ]
then
    if 


    fi
elif [ $# -eq 5 ]
then
    if [[ $1 == '--percentage' && $2 == '--all' && $3 == '--alphabet' ]]
    then

    fi
fi

So my question is do you have some suggestions, maybe do you know any command, that permit to manage easier the parameters ? There are many conditions to test with 4 parameters then how people do when parameters are 10 or 20 ?

Sevla
  • 67
  • 1
  • 10

1 Answers1

1

It's way better to parse args using case - where you can easily extract each and every argument. Here goes sample:

#!/bin/bash

ARG3=NO

for i in "$@"
do
case $i in
    -arg1=*|--argument1=*)
    ARG1="${i#*=}"
    shift # go to next arg=val
    ;;
    -arg2=*|--argument2=*)
    ARG2="${i#*=}"
    shift # go to next arg=val
    ;;
    --arg3)
    ARG3=YES
    shift # skip argument without value
    ;;
    *)
            # unknown option
    ;;
esac
done

if [ -z "$ARG1" ]; then
  echo "ARG1 can not be empty"
  exit 1
else
  if ! [[ $ARG1 =~ ^-?[0-9]+$ ]]; then
    echo "ARG1 must be a number"
    exit 1
  fi
fi

echo "ARG1  = ${ARG1}"
echo "ARG2  = ${ARG2}"
echo "ARG3  = ${ARG3}"
Oo.oO
  • 12,464
  • 3
  • 23
  • 45