Shell script to pass multiple arguments with options in command line

20,922

I believe using getopts is a better solution for advance use, when you need flexibility on the amount of arguments passed.

This is a working example:

if (($# == 0)); then
  echo "Please pass argumensts -p <pkg1><pkg2>... -m <email1><email2>.."
  exit 2
fi
while getopts ":p:m:" opt; do
  case $opt in
    p)
      echo "-p was triggered, Parameter: $OPTARG" >&2
      PKGS=$OPTARG
      ;;
    m)
      echo "-m was triggered, Parameter: $OPTARG" >&2
      MAIL=$OPTARG
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      exit 1
      ;;
  esac
done
echo "go thru selection"
for PKG in $PKGS;
do
 echo "ARG_PKG: $PKG"
done
echo "go thru selection email"
for M in $MAIL;
do
 echo "ARG_MAIL: $M"
done
exit 0

ref.. http://wiki.bash-hackers.org/howto/getopts_tutorial

OUTPUT:

bash t -p "pkg1 pkg2 pkg3" -m "[email protected] [email protected]"
-p was triggered, Parameter: pkg1 pkg2 pkg3
-m was triggered, Parameter: [email protected] [email protected]
go thru selection
ARG_PKG: pkg1
ARG_PKG: pkg2
ARG_PKG: pkg3
go thru selection email
ARG_MAIL: [email protected]
ARG_MAIL: [email protected]
Share:
20,922

Related videos on Youtube

Beginner
Author by

Beginner

Openstack Admin &amp; Linux System Admin

Updated on September 18, 2022

Comments

  • Beginner
    Beginner over 1 year

    I have the script, I need to execute this script like this:

    ./create_endpoint.sh --controller-ip 10.20.20.1 --controller-name User1.
    

    But its executing like this:

    ./create_endpoint.sh 10.20.20.1 User1
    

    The script:

    CONTROLLER_IP=""
    CONTROLLER_NAME=""
    if [ "$#" -eq 2 ]
      then
        CONTROLLER_IP=$1
        CONTROLLER_NAME=$2
      else
        echo "Usage : create_endpoint.sh --controller-ip <Controller IP> --controller-name"
        exit 1  
    fi
    echo $CONTROLLER_IP
    echo $CONTROLLER_NAME
    
  • Beginner
    Beginner over 6 years
    yeah, like above. Can you give some examples. Sometime I pass one argument or three arguments depends upon the requirement. how can i validate and execute
  • Suresh Raju
    Suresh Raju over 6 years
    if no of arguments will vary then check the $# -ge 2. Then check for not-null values.