[ "$input" == "N" -o "$input" == "n" ] && echo -e "you choice is: $input\n" && exit 0
echo -e "I don't know what your choice is" && exit 0
2.分支判断
两种常用的分支判断:if...else...fi分支判断,case...esac分支判断。 练习2:将练习1中的代码改写为if分支判断,使程序的执行逻辑更直观。
考查:==,||
if[]; then
...
elif[]; then
...
else
...
fi
#!/bin/bash
#Usage: user input a charector, program shows the different result.
#Author: Alfred Zhao
#Creation: 2015-05-06
#Version: 1.0.1
#1.Input 'Y' or 'N'
read -p "Input (y/n)" input
if [ "$input" == "Y" ] || [ "$input" == "y" ]; then
echo -e "you choice is: $input\n"
exit 0
elif [ "$input" == "N" ] || [ "$input" == "n" ]; then
echo -e "you choice is: $input\n"
exit 0
else
echo -e "I don't know what you choice is.\n"
exit 0
fi
练习3:用分支判断来辨别参数1的输入是否合法。
考查:$0,$1
#!/bin/bash
#Usage: To judge $1's>
#Author: Alfred Zhao
#Creation: 2015-05-07
#Version: 1.0.0
if [ "$1" == "Alfred" ]; then
echo -e "Authorization Successful! \n"
exit 0
elif [ "$1" == "" ]; then
echo -e "Waring: Authorization is null! ex> {$0 Username}\n"
exit 0
else
echo -e "Waring: Only Alfred can be authorized. ex> {$0 Alfred}\n"
exit 0
fi
练习4:用case判断改写练习3.
考查:case...esac判断
#!/bin/bash
#Usage: To judge $1's>
#Author: Alfred Zhao
#Creation: 2015-05-07
#Version: 1.0.1
case "$1" in
"Alfred")
echo -e "Authorization Successful! \n"
;;
"")
echo -e "Waring: Authorization is null! ex> {$0 Username}\n"
;;
*)
echo -e "Waring: Only Alfred can be authorized. ex> {$0 Alfred}\n"
;;
esac
3.循环结构 while do done, until do done(不定循环) 练习5:输入名字直到输入的名字是“Alfred”为止。
考查:while do done
#!/bin/bash
#Usage: Input the name until it is "Alfred".