
如果傳遞了諸如“-y”或“--yes”之類的特定參數,我想讓腳本成為非互動式並跳過使用者確認。我還想知道如何將參數傳遞給我來源的其他腳本。
SHORT=yq
LONG=yes,quick
PARSED=$(getopt --options $SHORT --longoptions $LONG --name "$0" -- "$@")
eval set -- "$PARSED"
q=0; autoConfirm=0
while true; do
case "$1" in
-q|--quick)
q=1
shift
;;
-y|--yes)
autoConfirm=1
shift
;;
--)
shift
break
;;
*)
echo "Invalid option. Use -h for help"
exit 3
;;
esac
done
assertConfirmation () {
local promptMsg=$1 autoConfirm=$2
if (( autoConfirm )); then
return
else
clear
read -n 1 -p "$promptMsg (yes/No) "
printf '\n========================================================================'
if [[ $REPLY =~ ^([Yy])$ ]]; then
return
fi
fi
return 1
}
if assertConfirmation "Install this?" "${autoConfirm:?}"; then
install
fi
source installation "${autoConfirm:?}" "${q:?}"
答案1
這取決於您的安裝腳本的期望。為了讓事情簡單,最好讓它接受-y
and-q
作為參數。這樣,您可以變更 case 語句,將q
和autoConfirm
設為-q
and-y
而不是 1(預設為 null),並將安裝腳本呼叫為:
source installation $autoConfirm $q
進行此更改後,請使用[[ $autoconfirm ]]
檢查它是否已設置,而不是(( autoConfirm ))
.