Advanced Bash script, and use the classic case
First, conditions are selected, it is determined
1, conditions are selected if
#!/bin/bash read -p "Please input your age: " age if [[ $age =~ [^0-9] ]] ;then echo "please input a int" exit 10 elif [ $age -ge 150 ];then echo "your age is wrong" exit 20 elif [ $age -gt 18 ];then echo "good good work,day day up" else echo "good good study,day day up" fi
Analysis: Enter the age, comprising first determining whether the input character other than numbers, there is, on the error; no, continue to determine whether less than 150, is greater than 18.
#!/bin/bash read -p "Please input your score: " score if [[ $score =~ [^0-9] ]] ;then echo "please input a int" exit 10 elif [ $score -gt 100 ];then echo "Your score is wrong" exit 20 elif [ $score -ge 85 ];then echo "Your score is very good" elif [ $score -ge 60 ];then echo "Your score is soso" else echo "You are loser" fi
Analysis: Enter the results, determines whether the input contains the first character other than numbers, there is, on the error; no, continue to determine whether or not greater than 100, is greater than 85, it is greater than 60.
2, conditional case
#!/bin/bash read -p "Please input yes or no: " anw case $anw in [yY][eE][sS]|[yY]) echo yes ;; [nN][oO]|[nN]) echo no ;; *) echo false ;; esac
Analysis: Enter yes or no, answer Y / y, yes Yes for the various combinations of case; Answer N / n, No for the various combinations of case no.
Two, four cycles
1、for
exp1 performed only once, while the equivalent embedded for years in
sum=0 read -p "Please input a positive integer: " num if [[ $num =~ [^0-9] ]] ;then echo "input error" elif [[ $num -eq 0 ]] ;then echo "input error" else for i in `seq 1 $num` ;do sum=$[$sum+$i] done echo $sum fi unset zhi
Analysis: sum initial value 0, enter a number, comprising first determining whether the input character other than numbers, there is, on the error; not determined whether 0, for entering the loop is not 0, i ranging from 1 to input the number of cycles of each sum = sum + i, the end of the cycle, the sum of the last output value.
② determined (1 + 2 + ... + 100) sum
for (( i=1,num=0;i<=100;i++ ));do [ $[i%2] -eq 1 ] && let sum+=i done echo sum=$sum
Analysis: i = 1, num = 0; if i <= 100, enter the circulation, if the modulo i ÷ 2 = 1, then the sum = sum + i, i = i + 1.
2、while
sum=0 i=1 while [ $i -le 100 ] ;do if [ $[$i%2] -ne 0 ];then let sum+=i let i++ else let i++ fi done echo "sum is $sum"
Analysis: sum initial value 0, i is the initial value of 1; Please enter a number, comprising first determining whether the input character other than numbers, there is, on the error; no when i <100, into the circulation, is determined i ÷ modulo 2 if not 0, an odd number is not 0, sum = sum + i, i + 1, is 0, i + 1; end of the loop, the final output value of the sum.
3, an until loop
until pgrep -u xiaoming &> /dev/null ;do sleep 0.5 done pkill -9 -u xiaoming
Analysis: scanning every 0.5 seconds, until you find xiaoming user logs on, kill the process, exit the script for monitoring user login.
4, the SELECT loop with the menu
PS3="Please choose the menu: " select menu in mifan huimian jiaozi babaozhou quit do case $REPLY in 1|4) echo "the price is 15" ;; 2|3) echo "the price is 20" ;; 5) break ;; *) echo "no the option" esac done
Analysis: PS3 prompt is select, automatically generated menu, select 5break exit the loop.
Third, in some usage cycle
1, loop control statements
#!/bin/bash sum=0 for i in {1..100} ;do [ $i -eq 51 ] && continue [ $[$i%2] -eq 1 ] && { let sum+=i;let i++; } done echo sum=$sum
Analysis: do cycle 2 + ... + 1 + 100, when i = 51, skip this cycle, but the entire cycle continues, the result is: sum = 2449
#!/bin/bash sum=0 for i in {1..100} ;do [ $i -eq 51 ] && break [ $[$i%2] -eq 1 ] && { let sum+=i;let i++; } done echo sum=$sum
Analysis: do cycle 2 + ... + 1 + 100, when 51 i =, out of the entire cycle, the result is: sum = 625
2, shift command control loop
#!/binbash if [ $# -eq 0 ] ;then echo "Please input a arg(eg:`basename $0` arg1)" exit 1 else while [ -n "$1" ];do useradd $1 &> /dev/null shift done fi
Analysis: If no input parameters (total parameter to 0), an error and exit; on the contrary, enter the circulation; if the first argument is not empty characters, create a user with the name of the first argument, and removes the first a parameter, followed by the parameters to the left as the first parameter, not until the first argument, quit.
#!/binbash while (( $# > 0 )) do echo "$*" shift done
3, the return value of the result
4、循环中可并行执行,使脚本运行更快
read -p "Please input network (eg:192.168.0.0): " net echo $net |egrep -o "\<(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\>" [ $? -eq 0 ] || ( echo "input error";exit 10 ) IP=`echo $net |egrep -o "^([0-9]{1,3}\.){3}"` for i in {1..254};do { ping -c 1 -w 1 $IP$i &> /dev/null && \ echo "$IP$i is up" }& done wait
分析:请输入一个IP地址例192.168.37.234,如果格式不是0.0.0.0 则报错退出;正确则进入循环,IP变量的值为192.168.37. i的范围为1-254,并行ping 192.168.37.1-154,ping通就输出此IP为UP。直到循环结束。
四、信号捕获trap
1、用法格式
2、常用信号
3、案例
#!/bin/bash trap 'echo press ctrl+c' 2 for ((i=0;i<10;i++));do sleep 1 echo $i done
分析:i=0,当i<10,每休眠1秒,i+1,捕获2信号,并执行echo press ctrl+c
② 打印0-3,ctrl+c不能终止,3之后恢复,能终止
#!/bin/bash trap '' 2 trap -p for ((i=0;i<3;i++));do sleep 1 echo $i done trap '-' SIGINT for ((i=3;i<10;i++));do sleep 1 echo $i done
分析:i=0,当i<3,每休眠1秒,i+1,捕获2信号;i>3时,解除捕获2信号。
五、脚本小知识(持续更新)
六、分享几个有意思的小脚本
1、9x9乘法表
#!/bin/bash for a in {1..9};do for b in `seq 1 $a`;do let c=$a*$b ;echo -e "${a}x${b}=$c\t\c" done echo done
2、彩色等腰三角形
#!/bin/bash read -p "Please input a num: " num if [[ $num =~ [^0-9] ]];then echo "input error" else for i in `seq 1 $num` ;do xing=$[2*$i-1] for j in `seq 1 $[$num-$i]`;do echo -ne " " done for k in `seq 1 $xing`;do color=$[$[RANDOM%7]+31] echo -ne "\033[1;${color};5m*\033[0m" done echo done fi
3、国际象棋棋盘
#!/bin/bash red="\033[1;41m \033[0m" yellow="\033[1;43m \033[0m" for i in {1..8};do if [ $[i%2] -eq 0 ];then for i in {1..4};do echo -e -n "$red$yellow"; done echo else for i in {1..4};do echo -e -n "$yellow$red"; done echo fi done
一、条件选择、判断
1、条件选择if
#!/bin/bash read -p "Please input your age: " age if [[ $age =~ [^0-9] ]] ;then echo "please input a int" exit 10 elif [ $age -ge 150 ];then echo "your age is wrong" exit 20 elif [ $age -gt 18 ];then echo "good good work,day day up" else echo "good good study,day day up" fi
分析:请输入年纪,先判断输入的是否含有除数字以外的字符,有,就报错;没有,继续判断是否小于150,是否大于18。
#!/bin/bash read -p "Please input your score: " score if [[ $score =~ [^0-9] ]] ;then echo "please input a int" exit 10 elif [ $score -gt 100 ];then echo "Your score is wrong" exit 20 elif [ $score -ge 85 ];then echo "Your score is very good" elif [ $score -ge 60 ];then echo "Your score is soso" else echo "You are loser" fi
分析:请输入成绩,先判断输入的是否含有除数字以外的字符,有,就报错;没有,继续判断是否大于100,是否大于85,是否大于60。
2、条件判断 case
#!/bin/bash read -p "Please input yes or no: " anw case $anw in [yY][eE][sS]|[yY]) echo yes ;; [nN][oO]|[nN]) echo no ;; *) echo false ;; esac
分析:请输入yes or no,回答Y/y、yes各种大小写组合为yes;回答N/n、No各种大小写组合为no。
二、四个循环
1、for
exp1只执行一次,相当于在for里嵌了while
sum=0 read -p "Please input a positive integer: " num if [[ $num =~ [^0-9] ]] ;then echo "input error" elif [[ $num -eq 0 ]] ;then echo "input error" else for i in `seq 1 $num` ;do sum=$[$sum+$i] done echo $sum fi unset zhi
分析:sum初始值为0,请输入一个数,先判断输入的是否含有除数字以外的字符,有,就报错;没有判断是否为0,不为0进入for循环,i的范围为1~输入的数,每次的循环为sum=sum+i,循环结束,最后输出sum的值。
② 求出(1+2+...+100)的总和
for (( i=1,num=0;i<=100;i++ ));do [ $[i%2] -eq 1 ] && let sum+=i done echo sum=$sum
分析:i=1,num=0;当i<=100,进入循环,若i÷2取余=1,则sum=sum+i,i=i+1。
2、while
sum=0 i=1 while [ $i -le 100 ] ;do if [ $[$i%2] -ne 0 ];then let sum+=i let i++ else let i++ fi done echo "sum is $sum"
分析:sum初始值为0,i的初始值为1;请输入一个数,先判断输入的是否含有除数字以外的字符,有,就报错;没有当i<100时,进入循环,判断 i÷2取余 是否不为0,不为0时为奇数,sum=sum+i,i+1,为0,i+1;循环结束,最后输出sum的值。
3、until 循环
until pgrep -u xiaoming &> /dev/null ;do sleep 0.5 done pkill -9 -u xiaoming
分析:每隔0.5秒扫描,直到发现xiaoming用户登录,杀死这个进程,退出脚本,用于监控用户登录。
4、select 循环与菜单
PS3="Please choose the menu: " select menu in mifan huimian jiaozi babaozhou quit do case $REPLY in 1|4) echo "the price is 15" ;; 2|3) echo "the price is 20" ;; 5) break ;; *) echo "no the option" esac done
分析:PS3是select的提示符,自动生成菜单,选择5break退出循环。
三、循环里的一些用法
1、循环控制语句
#!/bin/bash sum=0 for i in {1..100} ;do [ $i -eq 51 ] && continue [ $[$i%2] -eq 1 ] && { let sum+=i;let i++; } done echo sum=$sum
分析:做1+2+...+100的循环,当i=51时,跳过这次循环,但是继续整个循环,结果为:sum=2449
#!/bin/bash sum=0 for i in {1..100} ;do [ $i -eq 51 ] && break [ $[$i%2] -eq 1 ] && { let sum+=i;let i++; } done echo sum=$sum
分析:做1+2+...+100的循环,当i=51时,跳出整个循环,结果为:sum=625
2、循环控制shift命令
#!/binbash if [ $# -eq 0 ] ;then echo "Please input a arg(eg:`basename $0` arg1)" exit 1 else while [ -n "$1" ];do useradd $1 &> /dev/null shift done fi
分析:如果没有输入参数(参数的总数为0),提示错误并退出;反之,进入循环;若第一个参数不为空字符,则创建以第一个参数为名的用户,并移除第一个参数,将紧跟的参数左移作为第一个参数,直到没有第一个参数,退出。
#!/binbash while (( $# > 0 )) do echo "$*" shift done
3、返回值结果
4、循环中可并行执行,使脚本运行更快
read -p "Please input network (eg:192.168.0.0): " net echo $net |egrep -o "\<(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\>" [ $? -eq 0 ] || ( echo "input error";exit 10 ) IP=`echo $net |egrep -o "^([0-9]{1,3}\.){3}"` for i in {1..254};do { ping -c 1 -w 1 $IP$i &> /dev/null && \ echo "$IP$i is up" }& done wait
分析:请输入一个IP地址例192.168.37.234,如果格式不是0.0.0.0 则报错退出;正确则进入循环,IP变量的值为192.168.37. i的范围为1-254,并行ping 192.168.37.1-154,ping通就输出此IP为UP。直到循环结束。
四、信号捕获trap
1、用法格式
2、常用信号
3、案例
#!/bin/bash trap 'echo press ctrl+c' 2 for ((i=0;i<10;i++));do sleep 1 echo $i done
分析:i=0,当i<10,每休眠1秒,i+1,捕获2信号,并执行echo press ctrl+c
② 打印0-3,ctrl+c不能终止,3之后恢复,能终止
#!/bin/bash trap '' 2 trap -p for ((i=0;i<3;i++));do sleep 1 echo $i done trap '-' SIGINT for ((i=3;i<10;i++));do sleep 1 echo $i done
分析:i=0,当i<3,每休眠1秒,i+1,捕获2信号;i>3时,解除捕获2信号。
五、脚本小知识(持续更新)
六、分享几个有意思的小脚本
1、9x9乘法表
#!/bin/bash for a in {1..9};do for b in `seq 1 $a`;do let c=$a*$b ;echo -e "${a}x${b}=$c\t\c" done echo done
2、彩色等腰三角形
#!/bin/bash read -p "Please input a num: " num if [[ $num =~ [^0-9] ]];then echo "input error" else for i in `seq 1 $num` ;do xing=$[2*$i-1] for j in `seq 1 $[$num-$i]`;do echo -ne " " done for k in `seq 1 $xing`;do color=$[$[RANDOM%7]+31] echo -ne "\033[1;${color};5m*\033[0m" done echo done fi
3、国际象棋棋盘
#!/bin/bash red="\033[1;41m \033[0m" yellow="\033[1;43m \033[0m" for i in {1..8};do if [ $[i%2] -eq 0 ];then for i in {1..4};do echo -e -n "$red$yellow"; done echo else for i in {1..4};do echo -e -n "$yellow$red"; done echo fi done