Tuesday, January 16, 2007
Yes/No - BASH beginner
Some of the ways to write yes/no or confirmation code in BASH:
#Usual way:
echo -n "Do you want to exit ? (y/n)"
read ans
[ $ans == "y" ] && echo "Exiting ......" && sleep 2 && exit 0 || echo "Good"
#In a function:
f_yesno()
{
echo -n "Do you want to exit ? (y/n)"
read ans
[ $ans == "y" ] && return 0 || return 1
}
f_yesno && echo "exiting" && exit || echo "Not exiting"
echo "This is next line"
#One more way:
f_confirm() {
echo -n "$1 ? (n) "
read ans
case "$ans" in
y|Y|yes|YES|Yes) return 0 ;;
*) echo Exiting; return 1 ;;
esac
}
f_confirm "Delete?" && rm "/tmp/bashscript.out"
Points to digest:
1) Use of &&
2) return 0 implies success and non zero return value implies failure
3) Writing case in BASH
4) echo -n (do not output the trailing newline)
5) How to write a function in BASH
Subscribe to:
Post Comments (Atom)
© Jadu Saikia www.UNIXCL.com
No comments:
Post a Comment