美文网首页
循环语句

循环语句

作者: ALuckyLive | 来源:发表于2017-07-09 09:31 被阅读0次
循环控制语句---continue、break;
continue:
循环控制语句continue 依据条件跳过继续执行循环, ---continue 2---表示跳转到当前循环往外第二层循环;
用于循环体中continue【N】;提前结束N层的本轮循环,而直接进入下一轮判断;最内层为第一层
break:
循环控制语句break 终端,退出
用于循环体中
---break【N】;提前结束第N层循环,最内层为第一层
可以退出死循环;
#while true;do [ $i -eq 5 ] && break ;echo i=$i;sleep 0.3;let i++; done

if语句;
1、单分支
  if 判断条件;then
        条件为真的分支代码
  fi 
# if cmd1; then cmd2;fi;cmd3
####################################################  
cmd1执行成功,执行cmd2,接着执行cmd3
  
cmd1执行不成功,则不执行cmd2,跳过cmd2直接执行cmd3

####################################################

2、双分支
   
  if 判断条件:then
        条件为真的分支代码
  else
        条件为假的分支代码
  fi
3、多分支
  if   判断条件1;then
       条件为真的分之代码
  elif 判断条件2;then
       条件为真的分支代码
  elif 判断条件3:then
       条件为真的分支代码
  else
       以上条件都为假的分支代码
  fi
#################################################### 
#if cmd1:then cmd2;elif cmd3;then cmd4;elif cmd5;then cmd6;else cmdn;fi
 命令1执行成功接着执行命令2、如果命令1 执行不成功,将从新再次判断命令3是否成功、、、else指前面的全都不成功将执行命令N
####################################################

read -p "please input your age: " age
[[ ! "$age" =~ ^[[:digit:]]+$ ]] && echo please input digital && exit 10
#如果非数字,提示请输入数字,并且退出;

if [ "$age" -le 18 ]; then
     echo "you are baby"
#判断是否小于18,小于等于18则输出you are beby ,大于18则跳至下一行;
elif [ "$age" -gt 18 -a "$age" -le 60 ];then
     echo "you need work hard"
#判断年龄,判断大于18并小于等于60,则输出you need work hard.不在此范围则跳至下一行;
elif [ "$age" -le 80 ];then
     echo "you can enjoy the life"  
#判断是否小于等于80,则输出you can enjoy the life,大于80则跳至下一行;
else 
     echo "you will be lucky" 
#以上判断全部错误则输出you will be lucky;则表示大于80;
fi

-ge 是否大于等于

-le 是否小于等于

-eq 是否等于

-ne 是否不等于

-gt 是否大于

-lt 是否小于


.          匹配任意单个字符
[]         匹配指定范围内的任意单个字符
[^]        匹配指定范围外的任意单个字符
[:alnum:]  字母和 数字
[:alpha:]  代表任何英文大小写字符,亦即 A-Z, a-z
[:lower:]  小写字母 [:upper:]  大写字母
[:blank:]  空白字符(空格和制表符)
[:space:]  水平和垂直的空白字符(比[:blank:] 包含的范围广)
[:cntrl:]  不可打印的控制字符(退格、删除、警铃...) )
[:digit:]  字 十进制数字 [:xdigit:] 十六进制数字
[:graph:]  可打印的非空白字符
[:print:]  可打印字符
[:punct:]   标点符号

查看使用率
[root@centos6 ~]# df| sed -rn "/^\/dev\/sd/p"
/dev/sda2      100660656 4621768  90918888   5% /
/dev/sda3       50264772   53076  47651696   1% /app
/dev/sda1         991512   40312    900000   5% /boot

[root@centos6 ~]# df| sed -rn "/^\/dev\/sd/s/^.*[[:space:]]+(.*)%.*$/\1/p" 
5
1
5

[root@centos6 ~]# df
Filesystem     1K-blocks    Used Available Use% Mounted on
/dev/sda2      100660656 4621768  90918888   5% /
tmpfs             953636     228    953408   1% /dev/shm
/dev/sda3       50264772   53076  47651696   1% /app
/dev/sda1         991512   40312    900000   5% /boot
/dev/sr0         3878870 3878870         0 100% /media/CentOS_6.9_Final

[root@centos6 ~]# df |sed -rn '/^\/dev\/sd/s/^.*[[:space:]]+([[:digit:]]{1,3})%.*$/\1/p'   
5
1
5

case 语句

case支持glob风格的通配符:
*:任意长度任意字符
?:任意单个字符
[]:指定范围内的任意单个字符
a|b:a或b

case 变量引用 in
PAT1)
     分支1
      ;;
PAT2)
     分支2
      ;;
...
*)
     默认分支
      ;;
esac


[root@centos6 ~]#vim case.sh
#!/bin/bash
read -p "please input a digit " n
case $n in
1|3|5)         ------是1、3、5其中一个就输出cmd1
     echo cmd1
     ;;
2|4|6)
     echo cmd2
     ;;
10|20|30)
     echo cmd3
     ;;
*)            --------不符合上面条件时输出defoult cmd
     echo defoult cmd
esac

[root@centos6 ~]#. case.sh
please input a digit 2
cmd2
[root@centos6 ~]#. case.sh
please input a digit 3
cmd1
[root@centos6 ~]#. case.sh
please input a digit 4
cmd2
[root@centos6 ~]#. case.sh
please input a digit 7
defoult cmd
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
#!/bin/bash
read -p "Do you yue? " n
case $n in
1|3|5)
     echo cmd1
     ;;
2|4|6)
     echo cmd2
     ;;
[1-3]0)
     echo cmd3
     ;;
*)
     echo defoult cmd
esac

[root@centos6 ~]#vim yue.sh
read -p "yue bu yue? (yes or no) " ans
ans=`echo $ans |tr '[:upper:]' '[:lower:]'`----大小写转换赋值

case $ans in
y|ye|yes)
     echo ok,yue
     ;;
n|no)
     echo no,buyue
     ;;
esac
##########################################################
for循环
循环语句
for、 while、until
for 语句;
for 变量名 in 列表;do       变量名不加$
          循环体
;done

执行机制:
    依次将列表中的元素赋值给“变量名”;每次赋值后即执行一次循环体;直到列表中元素耗尽,循环结束;

for循环
列表生成方式:
  (1)直接给出列表
  (2)整数列表
       (a){start..end}
        (b) $(seq [start[step]] end)
   (3) 返回列表命令
         $(COMMAND)
   (4) 使用glob,如:*.sh
   (5) 变量引用-----------------------------!!!        
         $@ , $*
[root@centos6 ~]#for n in 1 2 5 7 8 ;do echo $n ;sleep 0.5 ;done
1
2
5
7
8
[root@centos6 ~]#for n in /var/log/*.log ;do echo "filename=`basename $n`" ;sleep 0.5 ;done 
filename=anaconda.ifcfg.log
filename=anaconda.log
filename=anaconda.program.log
filename=anaconda.storage.log
filename=anaconda.yum.log
filename=boot.log
filename=dracut.log
filename=mysqld.log
filename=pm-powersave.log
filename=spice-vdagent.log
filename=wpa_supplicant.log
filename=Xorg.0.log
filename=Xorg.1.log
filename=Xorg.2.log
filename=Xorg.9.log
filename=yum.log
###basename 只显示基名###
##########################################################
for循环
[root@centos6 ~]#sum=0;for i in {1..100..5};do let sum+=i;done;echo sum=$sum 
sum=970
相加
bc计算
[root@centos6 ~]#echo {1..100..5}
1 6 11 16 21 26 31 36 41 46 51 56 61 66 71 76 81 86 91 96
[root@centos6 ~]#echo {1..100..5}|tr " " "+"
1+6+11+16+21+26+31+36+41+46+51+56+61+66+71+76+81+86+91+96
[root@centos6 ~]#echo {1..100..5}|tr " " "+"|bc
970


![for特殊用法.png](https://img.haomeiwen.com/i6132998/b4eb7e187eb56eaa.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

##########################################################

ping -[options]

- w的最后期限
在ping退出之前,指定一个超时,
发送或接收的数据包少了。在
这种情况下,ping在发送数据包后不会停止,
它会等待最后期限到期,或者直到计数探针
对网络中的错误通知进行应答或发送。
-W超时
在几秒钟内等待响应。的选项
只影响任何反应的超时时间,其他的——
聪明的ping等待着两个rtt。

root@centos6 ~]#arp  查看MAC地址
Address                  HWtype  HWaddress           Flags Mask            Iface
172.17.252.218                   (incomplete)                              eth1
172.17.252.243                   (incomplete)                              eth1
192.168.239.1            ether   00:50:56:c0:00:01   C                     eth0
172.17.252.185                   (incomplete)                              eth1
172.17.252.28                    (incomplete)                              eth1
172.17.252.194                   (incomplete)                              eth1
172.17.252.15                    (incomplete)                              eth1

for语句特殊用法
for ((cmd1;cmd2;cmd3))
do
cmd4
done
[root@centos7 ~]#sum=0;for i in {1..100..2};do let sum+=i;done;echo sum=$sum
sum=2500
[root@centos7 ~]#for((sum=0,i=1;i<=100;i+=2));do let sum+=i;done;echo sum=$sum
sum=2500
[root@centos7 ~]#sum=0;i=1;while [ $i -le 100 ];do let sum+=i;let i+=2; done;echo sum=$sum
sum=2500
#################################################
nmap扫描端口    arp查看MAC地址
扫描端口;
[root@centos6 ~]#nmap -v -A 172.17.252.8

Starting Nmap 5.51 ( http://nmap.org ) at 2017-06-13 09:59 CST
NSE: Loaded 57 scripts for scanning.
Initiating ARP Ping Scan at 09:59
Scanning 172.17.252.8 [1 port]
Completed ARP Ping Scan at 09:59, 0.02s elapsed (1 total hosts)
Initiating Parallel DNS resolution of 1 host. at 09:59
Completed Parallel DNS resolution of 1 host. at 09:59, 6.61s elapsed
Initiating SYN Stealth Scan at 09:59
Scanning 172.17.252.8 [1000 ports]
Discovered open port 22/tcp on 172.17.252.8
Completed SYN Stealth Scan at 09:59, 5.09s elapsed (1000 total ports)
Initiating Service scan at 09:59
Scanning 1 service on 172.17.252.8
Completed Service scan at 09:59, 0.06s elapsed (1 service on 1 host)
Initiating OS detection (try #1) against 172.17.252.8
Retrying OS detection (try #2) against 172.17.252.8
NSE: Script scanning 172.17.252.8.
Initiating NSE at 09:59
Completed NSE at 09:59, 0.09s elapsed
Nmap scan report for 172.17.252.8
Host is up (0.0013s latency).
Not shown: 999 filtered ports
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 5.3 (protocol 2.0)
| ssh-hostkey: 1024 e3:96:d3:12:5d:13:49:3c:d2:16:c9:d8:40:14:fa:8a (DSA)
|_2048 f5:ea:a1:0c:c4:e7:b2:08:a7:7e:38:eb:c7:96:5c:a5 (RSA)
MAC Address: 00:0C:29:F7:2B:AD (VMware)
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Device type: specialized|WAP|general purpose
Running (JUST GUESSING): Crestron 2-Series (90%), Netgear embedded (90%), Linux 2.6.X (86%)
Aggressive OS guesses: Crestron XPanel control system (90%), Netgear DG834G WAP (90%), Linux 2.6.24 - 2.6.35 (86%), Linux 2.6.22 (85%), Linux 2.6.23 - 2.6.33 (85%), Linux 2.6.28 (Gentoo) (85%), Linux 2.6.31 - 2.6.34 (85%), Linux 2.6.9 - 2.6.27 (85%)
No exact OS matches for host (test conditions non-ideal).
Uptime guess: 0.124 days (since Tue Jun 13 07:00:56 2017)
Network Distance: 1 hop
TCP Sequence Prediction: Difficulty=262 (Good luck!)
IP ID Sequence Generation: All zeros

TRACEROUTE
HOP RTT     ADDRESS
1   1.29 ms 172.17.252.8

Read data files from: /usr/share/nmap
OS and Service detection performed. Please report any incorrect results at http://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 16.26 seconds
           Raw packets sent: 2059 (94.192KB) | Rcvd: 36 (3.228KB)

查看IP地址频通情况;
[root@centos7 bin]#cat IP2.sh
#!/bin/bash
up=0
down=0
net=172.17.252
for i in {1..100}
     do
     ping -c1 -W1 $net.$i &> /dev/null && { echo $net.$i is up;let ++up ; } || { echo $net.$i is down;let ++down ; }
done

echo the up host is $up
echo the host is $down

[root@centos7 bin]#ps -ax |grep IP2.sh
 11618 pts/2    S+     0:00 bash IP2.sh
 11700 pts/1    S+     0:00 grep --color=auto IP2.sh

##############################################
打印星;不换行
echo -e  \c

echo -n 
两种不换行
##############################################
[root@centos6 ~]#cat xing.sh
#!/bin/bash
x=16
y=8
for i in `seq $y`
do 
       for j in `seq $x`
       do   
            echo -e '*\c'
       done
       echo
done
[root@centos6 ~]#vim 9*9.sh 
#!/bin/bash
for i in `seq 9` ;do----i单一调出seq9列出的数字
       for j in `seq $i` ;do ---j单一调出seq $i列出的数字。
       let x=j*i  乘法运算
       echo -en "$j*$i=$x\t"
    done
       echo    
done

---\t为 TAB键为对齐---
echo -e为激活转义 -n 为不换行
[root@centos6 ~]#. 9*9.sh   
1=1
2=2     2=4
3=3     3=6     3=9
4=4     4=8     4=12    4=16
5=5     5=10    5=15    5=20    5=25
6=6     6=12    6=18    6=24    6=30    6=36
7=7     7=14    7=21    7=28    7=35    7=42    7=49
8=8     8=16    8=24    8=32    8=40    8=48    8=56    8=64
9=9     9=18    9=27    9=36    9=45    9=54    9=63    9=72    9=81

[root@centos6 ~]#vim 9*9.sh 
#!/bin/bash
for i in `seq 9` ;do
       for j in `seq $i` ;do
       let x=j*i
       echo -en "${j}x${i}=${x}\t"
    done
       echo    
done  

[root@centos6 ~]#. 9*9.sh   
1x1=1
1x2=2   2x2=4
1x3=3   2x3=6   3x3=9
1x4=4   2x4=8   3x4=12  4x4=16
1x5=5   2x5=10  3x5=15  4x5=20  5x5=25
1x6=6   2x6=12  3x6=18  4x6=24  5x6=30  6x6=36
1x7=7   2x7=14  3x7=21  4x7=28  5x7=35  6x7=42  7x7=49
1x8=8   2x8=16  3x8=24  4x8=32  5x8=40  6x8=48  7x8=56  8x8=64
1x9=9   2x9=18  3x9=27  4x9=36  5x9=45  6x9=54  7x9=63  8x9=72  9x9=81
[root@centos6 ~]#vim 9*9.2.sh
#!/bin/bash
for i in `seq 9` ;do
      for j in `seq $i`;do
      
            echo -ne "$i*$j=$[j*i]\t"  
                 
          done
      echo
done
~       
##############################################

[root@centos6 ~]#n=-20;[[ $n =~ ^-?[[:digit:]]+$ ]]&& echo true
true
[root@centos6 ~]#ans=Y;ans=`echo $ans |tr 'A-Z' 'a-z'`; [[ $ans =~ ^yes|y$ ]]&&echo yes
yes

双中括号支持正则表达式 
##############################################
三角形
read -p "请输入行数:" x
for i in `seq` $x ; do
      let a=2*i-1
      let b=x-i
      for k in seq $b ; do
      echo -n " "
      done
      for z in seq $a ; do
      echo -n "*"
      done
      echo
done
##############################################
2*第几行的编号=第几行的星的个数

总行数-当前行的编号=等于当前行的空格数
#############################################

[root@centos6 ~]#vim sanjiao.sh 
#!/bin/bash
read -p "请输入数字:" x
[[ !$x =~ [:digit:] ]] &&{  echo '请输入数字'; exit ; } || echo '等边三角形' 
  双中括号,是否包含,          看成整体,需加大括号;         
 
for i in `seq $x` ; do
     let a=x-i
     let b=2*i-1
    for z in `seq $a`; do 
           echo -n " "
              done 
    for y in `seq $b`; do
           echo -n "*"
               done
        echo
  done          
#################################################
while循环
while CONDITION ; do
       循环体
done

CONDITION: 循环控制条件;进入循环之前,先做一次判断;每一次循环之后会再次做判断;条件为“true”,则执行一次循环;直到条件测试状态为“false”终止循环
因此:CONDITION一般应该有循环控制变量;而此变量的值 会在循环体不断地陪修正
进入条件:CONDITION为true
退出条件:CONDITION为false
特殊用法
while 循环特殊用法
while read line ; do 
     循环体
done < /PATH/FROM/SOMEFILE
依次读取文件中的每一行,并将行赋值给变量line
#################################################
选取随机密码;
bDN9ajsv
[root@centos6 ~]#cat /dev/urandom |tr -dc 'a-zA-Z0-9'|head -c 8
#####################################
tr -dc -----删除并替换
#####################################
[root@centos6 ~]#vim while.sh
#!/bin/bash
i=1
while [ "$i" -le 10 ];do
      useradd user$i
      echo "user$i is created"
      password=`cat /dev/urandom |tr -dc 'a-zA-Z0-9'|head -c 8`
      echo $password |passwd --stdin user$i &> /dev/null
      let i++ ;
done
##########################################################
[root@centos6 ~]#chage -d0 user1
重设口令
[root@centos6 ~]#passwd -e user2
重设口令
##########################################################

until
#################################################
until CONDITION;do   倒序  until false; do
      循环体
                              循环体
done                         Done

#################################################
```
######continue ,break
```
循环控制语句continue ,break
用于循环中
continue [N];提前结束第N层的本轮循环,而直接进入下一轮判断;最内层为第一层

N --- 表示最外层循环;

#!/bin/bash
for i in {1..10}
do 
  [ $i -eq 5 ] && continue---结束本次循环
  echo i=$1
  sleep 0.5
done
echo test is finished
#!/bin/bash
for i in {1..10}
do 
  [ $i -eq 5 ] && break --- 结束整个循环
  echo i=$1
  sleep 0.5
done
echo test is finished

#################################################
```
######循环控制shift命令
```
shift [N]
用于将参量列表list 左移指定次数,缺省为左移一次。
参数列表 list 一旦被移动,最左端的那个参数就从列表中删除。while 循环遍历位置参量列表时,常用到shift
#################################################
```
######trap信号捕捉;
```
#!/bin/bash
trap 'echo int' int
trap -p
for i in {1..10};
do
    echo i=$i
    sleep 0.3
done
trap '' int
trap -p
for i in {11..20}
do
  echo i=$i
  sleep 0.3
done

trap '-' int   ---- 恢复信号,不再捕捉
trap -p
for i in {21..30}
do
  echo i=$i
  sleep 0.3
done

脚本;
#!/bin/bash
date1="Monday"
date2="Tuesday"
date3="Wednesday"
date4="Thursday"
date5="Friday"
date6="Saturday"
date7="Sunday"
for week in `date +%A`;do      date +%A 显示星期几
 if  [ $week==$date1 ];then    ==-----是否等于
    echo "This is $week" && ls -l
elif [ $week==$date2 ];then
    echo "Thsi is $week" && pwd
elif [ $week==$date3 ];then
    echo "This is $week" && cal
elif [ $week==$date4 ];then
    echo "This is $week" && tty
elif [ $week==$date5 ];then
    echo "this is $week" && id
elif [ $week==$date6 ];then
    echo "This is $week" && du -sh ---显示当前目录的总和大小
else
    echo "This is $week" && history -r ---将历史命令读入缓冲区中
fi
done
[root@centos7 app]#cal
      July 2017     
Su Mo Tu We Th Fr Sa
                   1
 2  3  4  5  6  7  8
 9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
[root@centos7 app]#tty
/dev/pts/1
[root@centos7 app]#id
uid=0(root) gid=0(root) groups=0(root) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
###统计文件行数;
[root@centos7 app]#vim wcfile.sh  
#!/bin/bash
read -p "please input a file way name or quit:" file
until [ $file == 'quit' ]; do  条件判断; 是否等于
      line=`cat $file | wc -l`
      echo "The file have a $line line!"
read -p "pieace input a file way name:" file
done
```
######select循环
```
select varible in list
do
 循环体命令
done
select 循环主要用于创建菜单,按数字顺序排列的才单项奖显示在标准错误上,并显示PS3提示符,等待用户输入
用户输入菜单中的某个数字,执行相应的命令
用户输入被保存在内置变量REPLY中

select menu in huimian hulatang yangtang
do
  [ -z "$menu" -o $menu= "exit" ] && break
  echo  your choose is  $menu
done

#################################################
```
######函数
```
  函数 {cmd;cmd;cmd}匿名函数;没有函数名
  #bash --version
   查看bash 版本

定义函数
函数有两个部分组成;函数名和函数体
语法一;function f_name{ 
             ...函数体...
}
语法二:function f_name (){
              ...函数体...

}

语法三;f_name (){
              ...函数体...
      
}

----定义函数 大括号里要隔开一个空格输入----

declare -f 显示函数

declare -f func2 也可以指定某个函数

declare -x 显示所有环境变量

unset func2  和取消变量一样
```
                                                  
#grep '^.*()' /etc/init.d/functions/

相关文章

网友评论

      本文标题:循环语句

      本文链接:https://www.haomeiwen.com/subject/tjlshxtx.html