1

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 

3 Answers 3

1

The correct syntax is like the following:

while [[ -n "$1" ]]; do case "$1" in -u | --username) USER="$2" ;; -p | --password) PASSWORD="$2" ;; -o | --out) OUT="$2" ;; -f | --file) PACKAGE="$2" ;; -g | --group) GROUP="$2" ;; -n | --name) NAME="$2" ;; -t | --test) TEST1="$2"; TEST2="$3"; shift 2 ;; -help | --help) help; exit 0 ;; download) ACTION="download" ;; delete) ACTION="delete" ;; * ) usage; exit 1 ;; esac shift done 

To pass multiple arguments separated by a space/spaces as a single parameter, make sure to quote them either with single/double quotes.

./script.sh -f 'something1 something2' 

or

./script.sh -f "something1 something2" 
Sign up to request clarification or add additional context in comments.

4 Comments

~  bash -x standalonetest.sh -u damn -p password + [[ -n -u ]] + case "$1" in + USER=-u + shift + [[ -n damn ]] + case "$1" in + echo usage usage + exit 1 Problem is that it always goes to usage and exits.
Copied your script and passing the arguments. It always ends in "usage" and exists
What I'm using is literally what I've wrote. Tested same scenario with the example you've given me, but it ends at " * ) usage; exit 1 ;;" and it exists
See my latest edited.
0

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

Comments

0

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" 

1 Comment

This works when adding quotes, indeed. I quess there is escaping double quotes. How can u add in the cases positional parameter. Like ./script sh something -n name. Can getopts do that? I couldn't properly see

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.