1

This question already has an answer here:

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

marked as duplicate by jimmij, Jeff Schaller, Stephen Rauch, Renan, peterh Dec 18 '17 at 2:41

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 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

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
  • 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
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

Not the answer you're looking for? Browse other questions tagged or ask your own question.