1

I am writing a simple bash script. My script installs ppa. The problem is I can't add two arguments. I want to write something simple like this:

./ppa.sh -i ppa:chris-lea/node.js nodejs

I tried this, but doesn't read the second argument 'nodejs'...

#! /bin/sh 
# Install/add PPA or Program 

while getopts ":i:e:" option;
do
 case $option in
  i)
   echo received -i with $OPTARG
ang='sudo apt-add-repository'
   ;;
  e)
   echo received -e with $OPTARG
ang='other line'
   ;;
  :)
   echo "option -$OPTARG needs an argument"
exit
   ;;
  *)
   echo "invalid option -$OPTARG" 
exit
   ;;
 esac

# done
    if [ "`echo $OPTARG | cut -d ':' -f1`" == "ppa" ]; then
echo 'is a ppa'
    $ang $OPTARG ; sleep 2s && sudo apt-get update; clear
        sudo apt-get -y install $OPTARG2
    fi
done
dr_
  • 28,763
  • 21
  • 89
  • 133
davidva
  • 160
  • 1
  • 5
  • 13
  • So `-i` takes two arguments? How many does `-e` take? Can they ever be mixed? – Mikel Mar 21 '14 at 12:54
  • @Mikel `-e` will remove the ppa and uninstall the package – davidva Mar 21 '14 at 16:08
  • I have solved it, and now work! only was necessary include a **new variable**: `OPTARG2=$( echo "$OPTARG" | awk '{ print $2 }')` and now work. **Also enclose with double quote:** `./ppa.sh -i "ppa:chris-lea/node.js nodejs"` – davidva Mar 21 '14 at 18:11

2 Answers2

3

Assuming -i means install, and takes two arguments, it's probably easier to just set the -i flag in your getopts block, then treat the arguments remaining after option processing as the repo and package, e.g.

while getopts ":i" option; do
    case "$option" in
    i)
        mode=install
        ;;
    esac
done

shift $((OPTIND - 1))

case "$mode" in
install)
    apt-add-repository "$1"
    apt-get update
    apt-get install "$2"
    shift 2
    ;;
esac

Or if the idea is to take a list of PPAs and packages, even more reason to do it this way, just make the last bit

case "$mode" in
install)
    for arg in "$@"; do
        case "$arg" in
            ppa:*)
                apt-add-repository "$arg"
                apt-get update
                ;;
            *)
                apt-get install "$arg"
                ;;
         esac
    done
    ;;
esac
Mikel
  • 56,387
  • 13
  • 130
  • 149
2

You should put two arguments in quote or double quote:

% ./ppa.sh -i 'ppa:chris-lea/node.js nodejs'
received -i with ppa:chris-lea/node.js nodejs
cuonglm
  • 150,973
  • 38
  • 327
  • 406
  • Thanks was necessary include a new variable: `OPTARG2=$( echo "$OPTARG" | awk '{ print $2 }')` and now work. And enclose the input with double quote `" "`. – davidva Mar 21 '14 at 18:22