Getopts

如何使用 getopts 輸入兩個參數?

  • July 13, 2017

我正在編寫一個簡單的 bash 腳本。我的腳本安裝ppa。問題是我不能添加兩個參數。我想寫一些像這樣簡單的東西:

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

我試過這個,但沒有讀取第二個參數’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

您應該將兩個參數放在引號或雙引號中:

% ./ppa.sh -i 'ppa:chris-lea/node.js nodejs'
received -i with ppa:chris-lea/node.js nodejs

假設-i意味著安裝,並接受兩個參數,在你的 getopts 塊中設置標誌可能更容易-i,然後將選項處理後剩餘的參數視為 repo 和包,例如

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

或者,如果想法是列出 PPA 和包,更有理由這樣做,只需做最後一點

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

引用自:https://unix.stackexchange.com/questions/120694