linux shell循环:for、while、until用法详解

2019-09-23 08:51:54刘景俊

退出条件:CONDITION为false

“:” 和true的返回值都为真

[root@centos6mini zuoye]# true
[root@centos6mini zuoye]# echo $?
0
[root@centos6mini zuoye]# :
[root@centos6mini zuoye]# echo $?
0

判断/var/目录下所有文件的类型

[root@centos6mini app]# cat linshi 
#!/bin/bash
dc=0
lc=0
cc=0
bc=0
oc=0
zc=0

ls -l /var |grep -v total >/tmp/var_ftype.txt
while read lines
do
  ftype=`echo $lines |awk '{print $1}' |cut -c 1`
  case $ftype in
    d) dname=`echo $lines |awk '{print $9}'`; echo "$dname is a Directory" ; let dc+=1;;
    l) lname=`echo $lines |awk '{print $9}'`; echo "$lname is a Links of Soft " ;let lc+=1 ;;
    c) cname=`echo $lines |awk '{print $9}'`; echo "$cname is a Character of file" ;let cc+=1;;
    b) bname=`echo $lines |awk '{print $9}'`; echo "$bname is a Block file" ; let bc+=1;;
    -) zname=`echo $lines |awk '{print $9}'`; echo "$zname is a common file" ; let zc+=1;;
    *) echo "Others files"; let oc+=1

  esac

done </tmp/var_ftype.txt
echo '-----------------------------' 
echo -e "var目录下普通文件数量: $zcnvar目录下子目录数量:$dcnvar目录下链接文件数量:$lcnvar目录下字符类型文件数量: $ccnvar
目录下块设备文件数量:$bcn其他类型文件数量:$oc"
rm -f /tmp/var_ftype.txt


[root@centos6mini app]# ./linshi 
cache is a Directory
crash is a Directory
cvs is a Directory
db is a Directory
empty is a Directory
games is a Directory
gdm is a Directory
lib is a Directory
local is a Directory
lock is a Directory
log is a Directory
mail is a Links of Soft 
nis is a Directory
opt is a Directory
preserve is a Directory
run is a Directory
spool is a Directory
tmp is a Directory
www is a Directory
yp is a Directory
-----------------------------
var目录下普通文件数量: 0
var目录下子目录数量:19
var目录下链接文件数量:1
var目录下字符类型文件数量: 0
var
目录下块设备文件数量:0
其他类型文件数量:0

编写脚本,求100以内所有正奇数之和

方法一:

[root@centos6mini zuoye]# echo {1..100..2}
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97 99
[root@centos6mini zuoye]# echo {1..100..2}|tr " " + |bc
2500

方法二:

[root@centos6mini 3.19]# ./1
2500
[root@centos6mini 3.19]# cat 1
#!/bin/bash
u=0 
for i in {1..100..2}; do
  let u+=i
done
echo $u

方法三:

[root@centos6mini 3.19]# ./1
2500
[root@centos6mini 3.19]# cat 1 
#!/bin/bash
u=0 
i=1
while [ $i -le 100 ] ;do

  let u+=i
  let i+=2
done
echo $u

编写脚本,提示请输入网络地址,如192.168.0.0,判断输入的网段中主机在线状态,并统计在线和离线主机各多少

方式一:

#!/bin/bash
w=0
a=0
y=0
for (( d=0;d<256;d++ ));do
  for (( f=1;f<255;f++ ));do
    {
    ping -c1 -w1 172.18."$d"."$f" &> /dev/null
    a=`echo $?`

    if [ $a -eq 0 ] ; then 
      echo "172.18."$d"."$f" up" >> /app/e.txt
      echo "172.18."$d"."$f" up "  
    fi
    if [ $a -ne 0 ] ; then 
            echo "172.18."$d"."$f" down " >> /app/r.txt
      echo "172.18."$d"."$f" down "         
    fi
  }&
  done
done 
w=`cat /app/e.txt |wc -l`
echo "通的 : $w"
y=`cat /app/r.txt |wc -l`
echo "不通的 : $y"
rm -rf /app/e.txt
rm -rf /app/w.txt