1,判断一个数字是否则在1,2,3之中.
#!/bin/bash
read -p "pls input a number:" n
case "$n" in
)
echo "变量是1"
;;
)
echo "变量是2"
;;
)
echo "变量是3"
;;
*)
echo "pls input a number between 1 and 3"
exit;
esac
2,多级if语句改写
#!/bin/bash
read -p "pls input a number:" n
if [ $n -eq ]; then
echo "$n是变量1"
elif [ $n -eq ]; then
echo "$n是变量2"
elif [ $n -eq ]; then
echo "$n是变量3"
else
echo "pls input a number between 1 and 3"
fi
3,if..else嵌套,实现
#!/bin/bash
read -p "pls input a number:" n
if [ $n -eq ]; then
echo
else
if [ $n -eq ]; then
echo
elif [ $n -eq ]; then
echo
else
echo "pls input a number [1-3]"
fi
fi
4,判断 分数等级
#!/bin/bash read -p "pls input score to test level:" score if [ $score -ge ]; then
echo "优秀"
elif [ $score -ge ]; then
echo "良好"
elif [ $score -ge ]; then
echo "中等"
elif [ $score -ge ]; then
echo "及格"
else
echo "不及格"
fi
5,给文字加颜色
#!/bin/bash
RED_COLOR='\e[1;31m'
GREEN_COLOR='\e[1;32m'
YELLOW_COLOR='\e[1;33m'
BLUE_COLOR='\e[1;34m'
RESET_COLOR='\e[0m' echo '
, 悟空
, 八戒
, 唐僧
, 白龙马
'
read -p "pls input a number:" n case $n in
)
echo -e "${RED_COLOR}悟空${RESET_COLOR}"
;;
)
echo -e "${GREEN_COLOR}八戒${RESET_COLOR}"
;;
)
echo -e "${YELLOW_COLOR}唐僧${RESET_COLOR}"
;;
)
echo -e "${BLUE_COLOR}白龙马${RESET_COLOR}"
;;
*)
echo "you need input a number in {1|2|3|4}"
esac
另一种写法:
#!/bin/bash
RED_COLOR='\e[1;31m'
GREEN_COLOR='\e[1;32m'
YELLOW_COLOR='\e[1;33m'
BLUE_COLOR='\e[1;34m'
RESET_COLOR='\e[0m' function menu(){
cat <<END
, 悟空
, 八戒
, 唐僧
, 白龙马
END
} function select_type(){
read -p "pls input a number:" n
case $n in
)
echo -e "${RED_COLOR}悟空${RESET_COLOR}"
;;
)
echo -e "${GREEN_COLOR}八戒${RESET_COLOR}"
;;
)
echo -e "${YELLOW_COLOR}唐僧${RESET_COLOR}"
;;
)
echo -e "${BLUE_COLOR}白龙马${RESET_COLOR}"
;;
*)
echo "you need input a number in {1|2|3|4}"
esac
} function main(){
menu
select_type
} main
读取命令行参数,给内容设置颜色
#!/bin/bash
RED_COLOR='\e[1;31m'
GREEN_COLOR='\e[1;32m'
YELLOW_COLOR='\e[1;33m'
BLUE_COLOR='\e[1;34m'
RESET_COLOR='\e[0m' if [ $# -ne ]; then
echo "Usage $0 input {red|green|yellow|blue}"
exit
fi case $ in
red)
echo -e "${RED_COLOR}$1${RESET_COLOR}"
;;
green)
echo -e "${GREEN_COLOR}$1${RESET_COLOR}"
;;
yellow)
echo -e "${YELLOW_COLOR}$1${RESET_COLOR}"
;;
blue)
echo -e "${BLUE_COLOR}$1${RESET_COLOR}"
;;
*)
echo "usage $0 input {red|green|yellow|blue}"
exit
esac
修改成函数调用方式
#!/bin/bash
function toColor(){
RED_COLOR='\e[1;31m'
GREEN_COLOR='\e[1;32m'
YELLOW_COLOR='\e[1;33m'
BLUE_COLOR='\e[1;34m'
RESET_COLOR='\e[0m' if [ $# -ne ]; then
echo "Usage $0 input {red|green|yellow|blue}"
exit
fi case $ in
red)
echo -e "${RED_COLOR}$1${RESET_COLOR}"
;;
green)
echo -e "${GREEN_COLOR}$1${RESET_COLOR}"
;;
yellow)
echo -e "${YELLOW_COLOR}$1${RESET_COLOR}"
;;
blue)
echo -e "${BLUE_COLOR}$1${RESET_COLOR}"
;;
*)
echo "usage $0 input {red|green|yellow|blue}"
exit
esac
} function main(){
toColor $ $
} main $*