我正在写一个简单的 bash 脚本。我的脚本安装聚苯胺。问题是我无法添加两个参数。我想写一些简单的东西,如下所示:
./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
答案1
假设意味着安装,并且需要两个参数,那么在 getopts 块中-i
设置标志可能更容易,然后将选项处理后剩余的参数视为存储库和包,例如-i
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
答案2
您应该将两个参数放在引号或双引号中:
% ./ppa.sh -i 'ppa:chris-lea/node.js nodejs'
received -i with ppa:chris-lea/node.js nodejs