Home > Mobile >  Simplest way to pass multivalue arguments
Simplest way to pass multivalue arguments

Time:02-18

Trying to make this work I have a script which needs to get a multi value argument separated by space

e.g ./script.sh  -f something1 something2
while [[ $1 -gt 0 ]]; do
    case $1 in
    -u | --username )   shift
                              USER=$1 ;;
    -p | --password )  shift
                              PASSWORD=$1 ;;
    -o | --out )       shift
                              OUT=$1  ;;
    -f | --file )  shift
                              PACKAGE=$1 ;;
    -g | --group )     shift
                              GROUP=$1  ;;
    -n | --name )      shift
                              NAME=$1  ;;
    -help | --help )      help
                                       ;;
    download )         ACTION="download"
                ;;
    delete )           ACTION="delete"
                ;;
    * )                usage   exit 1
    esac
    shift
done

CodePudding user response:

There's already a shell builtin for such cases - getopts (not getopt) https://www.mkssoftware.com/docs/man1/getopts.1.asp

CodePudding user response:

You can try something like this:

#!/bin/bash
while getopts ":n:u:" opt
do
  case $opt in
    n) name="$OPTARG" ;;
    u) user="$OPTARG" ;;
    \?) echo "Invalid option -$OPTARG" >&2
    exit 1 ;;
  esac
done

echo "Name: $name"
echo "User: $user"
  • Related