for 变量 in 列表;
循环体
done
如何生成列表;
{1..100}
seq [起始数][步长]结束值;
#!/bin/bash
lines=`cat /etc/passwd |wc -l`
for i in `seq 1 $lines`;
do
user=`cut -d: -f1 /etc/passwd | head -$i | tail -1`
echo "hello:$user"
done
输出shell为bash的用户
#!/bin/bash
lines=`cat /etc/passwd |wc -l`
for i in `seq 1 $lines`;
do
#user=`cut -d: -f1 /etc/passwd`
user=`cut -d: -f1 /etc/passwd | head -$i | tail -1`
shell=`cut -d: -f7 /etc/passwd | head -$i | tail -1`
if grep '\<bash\>' $shell &>/tmp/out.txt ;then
echo "hello:$user,your shel:$shell"
fi
done
添加删除十个用户
#!/bin/bash
#
if [ $1 == add ]&>/tmp/out.txt ;then
for i in {1..10};do
useradd $i
done
echo "useradd finish"
elif [ $1 == del ]&>/tmp/out.txt ;then
for i in {1..10};do
userdel -r $i
done
echo "userdell finish"
else
echo "please use add or del"
fi
判断ESTABLEISHED和LISTEN的个数
#!/bin/bash
#
declare -i estab=0
declare -i listen=0
declare -i other=0
for stat in $(netstat -tan | grep '^tcp\>' | awk '{print $NF}');do
echo $stat
if [ "$stat" == 'ESTABLISHED' ];then
let estab++
elif [ "$stat" == 'LISTEN' ];then
let listen++
else
let other++
fi
done
echo $estab
echo $listen
echo $other
判读路径下所有文件的类型
#!/bin/bash
#
for file in `ls /var`; do
if [ -f /var/$file ];then
echo "Common file."
elif [ -L /var/$file ];then
echo "Symbolic file"
elif [ -d /var/$file ];then
echo "Directory"
else
echo "Other type"
fi
done
判断服务器网络是否能ping通
#!/bin/bash
#
echo "" >/root/ping.log
for i in `seq 1 15`;do
ping -w 1 172.16.6.$i&>/dev/null
if [ $? -eq 0 ];then
echo "172.16.6.$i is online" | tee -a /root/ping.log
else
echo "172.16.6.$i is down" | tee -a /root/ping.log
fi
done
echo "online is `cat ping.log | grep online | wc -l`"
echo "down is `cat ping.log | grep down | wc -l`"
打印菱形
#!/bin/bash
#
let number=$1%2
if [ $number -eq 0 ];then
echo "Please enter odd Numbers"
else
let kk=$1/2
let hh=1
for ((i=1;i<=$1;i+=2));do
for((k=1;k<=$kk;k++));do
echo -e -n " "
done
for ((y=1;y<=$i;y++));do
echo -e -n "*"
done
echo
let kk-=1
done
for ((j=$1-2;j>=1;j-=2));do
for((h=1;h<=$hh;h++));do
echo -e -n " "
done
for ((x=1;x<=$j;x++));do
echo -e -n "*"
done
echo
let hh+=1
done
fi
本文转自阿伦艾弗森 51CTO博客,原文链接:http://blog.51cto.com/perper/1947649,如需转载请自行联系原作者