🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
一)for循环 循环体:要执行的代码 进入条件: 满足条件 退出条件: 不满足条件 使用方法: for 变量名 in 列表;do 循环体 done 案例: #!/bin/bash IP=$(cat /server/scripts/ip.txt | awk -F . '{print $4}') for i in $IP ;do ping -c 1 10.2.11.$i &>/dev/null if [ $? -eq 0 ];then echo "10.2.11.$i successful" >> /tmp/test2.log fi done ~ 列表生成方式有如下 1) 读取某个文件 2) 直接给出字符串列表(item01 item02 item03) 3) 使用步进({1..10}) 4)使用 seq 首数 步进 尾数 ( $(seq 2 2 10)) 5)使用ls 显示列表,比如($(ls /var)) for file in $(ls /var);do if [ -f /var/$file ];then echo "a common file" elif [ -d /var/$file ];then echo "a dir file" else echo "other file" fi done 6) 变量引用 ($@,$*) declare -i estab=0 declare -i listen=0 declare -i other=0 for state in $( netstat -tna|grep "^tcp\>"|awk -F' ' '{print $NF}');do if [ "$state" == "ESTABLISHED" ];then let estab++ elif [ "$state" == "LISTEN" ];then let listen++ else let other++ fi done echo "ESTABLISHED file you $estab" echo "LISTEN file you $listen" echo "OTHER file you $other" #!/bin/bash for file in $(ls /etc/rc.d/rc3.d/);do cd /etc/rc.d/rc3.d/ if [ "${file:0:1}" == "K" ];then echo "$file stop" elif [ "${file:0:1}" == "S" ];then echo "$file start" else echo "error" fi done ~ #!/bin/bash mima=( 21029299 00205d1c a3da1677 1f6d12dd ) for i in {1..32767};do name=$(echo $i | md5sum|cut -c -8) for n in ${mima[*]};do if [ "$name" == "$n" ];then echo "$i match $n" fi done done ~ 二) while循环 while CONDITION;do 循环体 done 当CONDITION条件为真,则进入循环体,当条件为假,则退出循环体 #!/bin/bash declare -i i=1 declare -i online=0 declare -i downline=0 while [ $i -lt 20 ];do if ping -c 1 10.2.11.$i &>/dev/null ;then echo "10.2.11.$i online" let online++ else echo "10.2.11.$i downline" let downline++ fi let i++ done echo "online computer has $online" echo "downline computer has $downline" 打印九九乘法口诀 #!/bin/bash for j in {1..9};do for i in $(seq 1 $j);do echo -e -n "$[i]*$[j]=$[$i*$j]\t" done echo done declare -i i=0 declare -i j=0 while [ $j -le 9 ];do while [ $i -le $j ];do echo -n -e "$[i]*$[j]=$[$i*$j]\t" let i++ done echo let i=1 let j++ done continue 【N】 提前结束第N层的本轮循环,直接进入下一轮循环 break 【N】 提前结束循环 创建死循环