1.不用if,实现比较两个数字大小的功能
cat compare1.sh #!/bin/bash [ $# != 2 ] && { echo "USAGE:scripts.sh Arg1 Arg2" exit 1 } expr $1 + 1 &>/dev/null [ `echo $?` -ne 0 ] && { echo "First Arg isn't int." exit 2 } expr $2 + 1 &>/dev/null [ `echo $?` -ne 0 ] && { echo "Second Arg isn't int." exit 3 } [ $1 -lt $2 ] && { echo "$1" "<" "$2" exit 0 } [ $1 -gt $2 ] && { echo "$1" ">" "$2" exit 0 } [ $1 -eq $2 ] && { echo "$1" "=" "$2" exit 0 }
2.精简版(exit后面得跟分号,命令不能紧挨着花括号,得有空格)
cat compare2.sh #!/bin/bash [ $# != 2 ] && { echo "USAGE:scripts.sh Arg1 Arg2";exit 1; } expr $1 + 1 &>/dev/null [ `echo $?` -ne 0 ] && { echo "First Arg isn't int.";exit 2; } expr $2 + 1 &>/dev/null [ `echo $?` -ne 0 ] && { echo "Second Arg isn't int.";exit 3; } [ $1 -lt $2 ] && { echo "$1" "<" "$2";exit 0; } [ $1 -gt $2 ] && { echo "$1" ">" "$2";exit 0; } [ $1 -eq $2 ] && { echo "$1" "=" "$2";exit 0; } # 除了expr,也可以这样判断输入的参数是否为整数 len = `echo "$1" | sed 's#[0-9]##g'` [ -n $len ] && { echo "First Arg isn't int.";exit 2; }
3.一级菜单
#!/bin/bash menu(){ cat<<EOF 1.[install lamp] 2.[install lnmp] 3.[exit] echo "pls input num: " EOF } menu read num lamp="/server/scripts/install_lamp.sh" lnmp="/server/scripts/install_lnmp.sh" [ $num -eq 1 ] && { [ -x "$lamp" ] || { echo "$lamp can't be exec";exit 1; } echo "start installing lamp" $lamp exit 0 } [ $num -eq 2 ] && { [ -x "$lnmp" ] || { echo "$lnmp can't be exec";exit 1; } echo "start installing lnmp" $b exit 0 } [ $num -eq 3 ] && { echo "you choice quit!" exit 0 } echo "input error";exit 1
4.监控网站是否异常
#!/bin/bash [ -f /etc/init.d/functions ] && . /etc/init.d/functions usage(){ echo "USAGE:$0 url" exit 1 } # -T超时时间,-t测试次数 RETVAL=0 CheckUrl(){ wget -T 10 --spider -t 2 $1 &>/dev/null RETVAL=$? if [ $RETVAL -eq 0 ];then action "$1 url" /bin/true else action "$1 url" /bin/false fi return $RETVAL } main(){ if [ $# -ne 1 ];then usage fi CheckUrl $1 } main $*
5.给字符串加颜色
颜色范围30-37:{'30':'黑色','31':'红色','32':'绿色','33':'黄色','34':'蓝色','35':'紫色','36':'天蓝','37':'白色',}
echo -e "\033[32m 绿色 \033[0m"
背景颜色范围40-47,依次是黑底、红底、绿底、黄底、蓝底、紫底、天蓝、白底
echo -e "\033[42;37m 绿底白字 \033[0m"
cat fruit-color.sh #!/bin/bash RED_COLOR='\E[1;31m' GREEN_COLOR='\E[1;32m' YELLOW_COLOR='\E[1;33m' BLUE_COLOR='\E[1;34m' PINK='\E[1;35m' SHAN_SHUO='\E[31;5m' RES='\E[0m' menu(){ cat <<EOF 1.apple 2.pear 3.banana 4.cherry 5.exit EOF read -p "Pls input a num: " fruit } usage(){ echo "USAGE:$0 {red|green|yellow}" contents exit 1 } color(){ case "$fruit" in 1) echo -e "${RED_COLOR}apple $RES" ;; 2) echo -e "${GREEN_COLOR}pear $RES" ;; 3) echo -e "${YELLOW_COLOR}banana $RES" ;; 4) echo -e "${BLUE_COLOR}cherry $RES" ;; 5) exit 1 ;; *) usage esac } main(){ while true do menu color done } main