1.流程控制语句case
case 变量或表达式 in
变量或表达式1)
执行体;;
变量或表达式2)
执行体;;
*)
默认执行体
esac
case $var in
1|a|c)
echo "您输入了1或a或c";;
2|b)
echo "您输入了2或b"
*)
echo "您输入了其它内容"
esac
2.循环语句for-do-done
语法格式
for var in list
do
commands
done
或
for var in list;do
commands
done
例1:
#!/bin/bash
for var in a1 b1 c1 d1
do
echo the text is $var
done
例2:
#!/bin/bash
for var in a1 b1 'c1 d1'e2 'hello world'
do
echo the text is $var
done
例3:变量中取值
#!/bin/bash
list="a1 b1 c1 d1"
for i in $list
do
echo is a $i
done
例4:命令中取值,以空格做分隔符
#!/bin/bash
for i in `cat /etc/hosts`
do
echo "$i"
done
- 自定义shell分隔符
IFS=: 以:冒号做分隔符,可以指定多个
IFS='\n:;"' 将反斜杠 n 冒号 分号 双引号作为分隔符
IFS='\n' 将字符\和字符n作为字段分隔符
IFS=$'\n' 使用换行符作为字段分隔符
例5:指定以\n回车作为for语句的分隔符
#!/bin/bash
IFS=$'\n'
for i in `cat /etc/hosts`
do
echo "$i"
done
例6:C语言风格的for
for ((i=0;i<=10;i++))
do
echo num is $i
done
- while循环语句和循环嵌套
语法格式如下
while 测试命令
do
commands
done
例1:降序输出10到1的数字
#!/bin/bash
var=10
#while [ $var -gt 0 ];do
while (( var>=0 ));do
echo $var
#var=$[$var-1]
#var=$((var-1))
#((var=var-1))
let var--
done
- 嵌套循环
例1:批量添加a.txt文件5个用户
echo mk cd ls find ln > a.txt
#!/bin/bash
#for name in $(cat /root/a.txt);do
for name in `cat /root/a.txt`;do
id $name &> /dev/null
if [ $? -ne 0 ];then
useradd $name
echo "123456" | passwd --stdin $name &> /dev/null
echo "user $name created"
else
echo "user $name is exist"
fi
done
例2:打印九九乘法表
#!/bin/bash
for i in `seq 9`
do
for j in `seq $i`
do
echo -n "$i*$j=`echo $(($i*$j))`"
done
echo ""
done
- 将/opt目录下所有日志文件全自动打包
vim log-back.sh
#!/bin/bash
SRC_DIR=/var/log/
DES_DIR=/opt/backup/`date +%Y%m%d`
if [ ! -d $DES_DIR ];then
mkdir -p $DES_DIR
fi
for i in `find $SRC_DIR -name "*.log"
for i in `find $SRC_DIR -name
do
tar czf $i.tgz $i
done
mv /var/log/*.tgz $DES_DIR
ls -lh $DES_DIR
echo "The scripts exec end,Files tar successfully!"
- 找出192.168.1.1-10网段中,服务器已经关机的IP地址
vim ping.sh
#!/bin/bash
i=1
for ((i=1;i<10;i++))
do
ping -c 3 192.168.0.$i &> /dev/null
if [ $? -ne 0 ];then
echo 192.168.0.$i is shutdown
fi
done
- 批量创建账号并生成随机密码
vim adduser.sh
#!/bin/bash
for i in hello{1..10}
do
id $i &> /dev/null
if [ ! $? -eq 0 ];then
useradd $i
pass=`date +%s|md5sum|cut -c 1-8`
sleep 1
echo "$i:$pass" >> /opt/passwd.log
echo $pass|passwd --stdin $i &> /dev/null
if [ $? -eq 0 ];then
echo "create user $i is successfully!"
else
echo "create user $i is failed!"
fi
else
echo "this is user $i exist"
fi
done