-2

I want to be able to run my script with one or more arguments and perform an action for all arguments passed.

So far, I have been able to run a command based on the first argument as follows:

#/bin/bash

ap=admin
lp=lender

if [[ "$1" = "ap" ]]; then
    echo "### pulling $ap ###"
elif [[ "$1" = "lp" ]]; then
    echo "### pulling $lp ###"
else 
echo "There is no service with that name"
fi

I want to be able to run my script with more than one argument as follows and run the commands needed for each of the arguments given. For example, if I run this:

./update.sh ap lp

I want to be able to detect both ap and lp and then execute the correct commands.

To summarise, if the person running the script passes 'ap' as the argument, I want to pull admin and if the user passes both 'ap' & 'lp' as the arguments, I want to pull both admin and lender.

Thanks in advance for your help!

4ae1e1
  • 6,750
  • 7
  • 42
  • 73
user3507094
  • 224
  • 2
  • 13
  • Have a look here for a very readable, maintainable, extensible, standards-based approach... http://stackoverflow.com/a/16496491/2836621 – Mark Setchell Nov 24 '15 at 12:21
  • 1
    Kudos, though, for actually checking the value of `$1`, rather than simply trying to execute whatever it happens to be with something like `"$1"` or `eval "$1"`. – chepner Nov 24 '15 at 12:30

2 Answers2

2

Use a while loop to look through the arguments and use shift to move arguments $N+1 to $N. So after a shift the second argument becomes the first.

while [ "$#" -gt 0 ]
do
  if [[ $1 = "ap" ]]
  then
    echo "AP typed"
  elif [[ $1 = "lp" ]]
  then
    echo "LP typed"
  fi
  shift
done
chepner
  • 446,329
  • 63
  • 468
  • 610
Neil Masson
  • 2,549
  • 1
  • 14
  • 22
0
while [[ $# -gt 0 ]]
   do
       key="$1"
       case $key in
       ap)
               echo "### pulling $ap ###"

       ;;
       lp)
               echo "### pulling $lp ###"

       ;;
       *)
           echo "There is no service with that name"
       ;;
esac
shift
done

this will accept arguments in every order you put them

 $ ./update lp ap
 $ ./update ap lp
 $ ./update lp
 $ ./update ap
nautilor
  • 106
  • 11
  • You have too many shifts if `$1` matches an expected command. Either move the `shift` following the case statement to the `*` case, or remove the calls to `shift` from `ap` and `lp`. – chepner Nov 24 '15 at 14:42