0

I have a shell script which takes 1 mandatory argument and upto 3 optional arguments and I want to enhance the script by able to pass one more additional argument without breaking the current design . That is if my argument is n and existing arguments are a and b c and d the following should work

./script.sh a b c d n
./script.sh a n
./script.sh a b n
./script.sh a b c n
5
  • 2
    OK. what is your current design? Commented Feb 11, 2014 at 19:12
  • a1=$1 a2=$2 a3=$3 a4=$4 var=($a1 $a2 $a3 $a4) for i in ${var[*]} Commented Feb 11, 2014 at 19:24
  • @sudeep, use "${var[@]}" for iterating over arrays -- ${var[*]} concatenates into a scalar, then string-splits and glob-expands it. Commented Feb 11, 2014 at 19:35
  • ...to see what that means in practice, try passing a single argument with "two words". Commented Feb 11, 2014 at 19:36
  • How about: var=( "$@" ) -- then you can have however many arguments you need. Commented Feb 11, 2014 at 19:51

2 Answers 2

1

You could check if the last argument is n. If so, remove it from the argument list and add the rest to an array, else add all the arguments to an array.

if [[ "${@: -1}" = n ]]; then
  for j in "${@:1:$(($#-1))}"; do
    var+=($j)
  done
else
  for j; do
    var+=($j)
  done
fi

echo "${var[@]}"

This would produce:

a b c

when the arguments to the script are a b c and a b c n.

Sign up to request clarification or add additional context in comments.

Comments

0

Not elegant, but straightforward:

case $# in
    0|1) printf >&2 "Too few arguments\n"; exit 1
         ;;
    2) first=$1
       second=$2
       ;;
    3) first=$1
       optional_a=$2
       second=$3
       ;;
    4) first=$1
       optional_a=$2
       optional_b=$3
       second=$4
       ;;
    5) first=$1
       optional_a=$2
       optional_b=$3
       optional_c=$4
       second=$5
       ;;
    *) printf >&2 "Too many optional arguments\n"; exit 1
       ;;
esac

The two required arguments are in first and second; the three optional arguments are in optional_a, optional_b, and optional_c, respectively.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.