Deep dive into Kernel
홈
태그
미디어로그
위치로그
방명록
Passion/bash
bash에서 yes no 질문
sunshout
2009. 12. 9. 11:10
bash 쉘에서 interactive 하게 실행하고 싶을 때
yes or no 질문이 많이 사용된다.
이를 위한 스크립트는 다음과 같다.
fuction yesno
(Language : text)
#/bin/bash
###################################################
# Print warning message.
function
warning
()
{
echo
"$*"
>&2
}
####################################################
# Print error message and exit.
function
error
()
{
echo
"$*"
>&2
exit
1
}
##############################
# yesno question
# --default (yes or no)
# --timeout (xx seconds)
# ex)
# if yesno --default no --timeout 10 "Your question(default no, timeout 10)?"; then
# echo "Yes"
# else
# echo "No"
#fi
##############################
function yesno()
{
local ans
local ok=0
local timeout=0
local default
local t
while [[ "$1" ]]
do
case "$1" in
--default)
shift
default=$1
if [[ ! "$default" ]]; then error "Missing default value"; fi
t=$(tr '[:upper:]' '[:lower:]' <<<$default)
if [[ "$t" != 'y' && "$t" != 'yes' && "$t" != 'n' && "$t" != 'no' ]]; then
error "Illegal default answer: $default"
fi
default=$t
shift
;;
--timeout)
shift
timeout=$1
if [[ ! "$timeout" ]]; then error "Missing timeout value"; fi
if [[ ! "$timeout" =~ ^[0-9][0-9]*$ ]]; then error "Illegal timeout value: $timeout"; fi
shift
;;
-*)
error "Unrecognized option: $1"
;;
*)
break
;;
esac
done
if [[ $timeout -ne 0 && ! "$default" ]]; then
error "Non-zero timeout requires a default answer"
fi
if [[ ! "$*" ]]; then error "Missing question"; fi
while [[ $ok -eq 0 ]]
do
if [[ $timeout -ne 0 ]]; then
if ! read -t $timeout -p "$*" ans; then
ans=$default
else
# Turn off timeout if answer entered.
timeout=0
if [[ ! "$ans" ]]; then ans=$default; fi
fi
else
read -p "$*" ans
if [[ ! "$ans" ]]; then
ans=$default
else
ans=$(tr '[:upper:]' '[:lower:]' <<<$ans)
fi
fi
if [[ "$ans" == 'y' || "$ans" == 'yes' || "$ans" == 'n' || "$ans" == 'no' ]]; then
ok=1
fi
if [[ $ok -eq 0 ]]; then warning "Valid answers are: yes y no n"; fi
done
[[ "$ans" = "y" || "$ans" == "yes" ]]
}
공유하기
게시글 관리
Deep dive into Kernel
티스토리툴바
Deep dive into Kernel
구독하기