一.for 循环
for 定义变量
do 使用变量,执行动作
done 结束标志
格式1:
1 #!/bin/bash
2 for NUM in `seq 1 2 10` ##从1到10循环,一次跳两个数
3 do
4 echo $NUM
5 done
格式2:
1 #!/bin/bash
2 for NUM in 2 6 7 8 0
3 do
4 echo $NUM
5 done
格式3:
1 #!/bin/bash
2 for NUM in {1..10}
3 do
4 echo $NUM
5 done
格式4:
1 #!/bin/bash
2 for ((NUM=0;NUM<10;NUM++))
3 do
4 echo $NUM
5 done
二.while
1 #!/bin/bash
2 while true #条件为真
3 do #条件成立所作循环动作
4 read -p "please input word:" WORD
5 echo $WORD
6 done
三.until
1 #!/bin/bash
2 until false #条件为假
3 do #条件不成立所作循环动作
4 read -p "please input word:" WORD
5 echo $WORD
6 done
四.if
if #条件
then
##做的动作
elif #条件
then
##做的动作
...
else
##做的动作
fi #结束if
1 #!/bin/bash
2 if [ -z "$1" ]
3 then
4 echo error
5 elif [ "$1" = "westos" ]
6 then
7 echo linux
8 elif [ "$1" = "linux" ]
9 then
10 echo westos
11 else
12 echo unknow
13 fi
脚本练习:
check_file.sh
please input filename: file
file is not exist
file is file
file is direcory
此脚本会一直询问直到用户输入exit为止
1 #!/bin/bash
2 while true
3 do
4 read -p "please input filename:" FILE
5 if [ "$FILE" = "exit" ]
6 then
7 exit
8 elif [ ! -e "$FILE" ]
9 then
10 echo $FILE is not exist!
11 elif [ -f "$FILE" ]
12 then
13 echo $FILE is file
14 elif [ -d "$FILE" ]
15 then
16 echo $FILE is directory
17 else
18 echo $FILE unknow
19 fi
20 done
五.case
case $1 in
word1|WORD1)
action1
;;
word2|WORD2)
action2
;;
*)
action3
esac
脚本练习
system_watch.sh disk memory upload (每秒显示)
disk 监控磁盘使用情况
memory 监控内存使用情况
upload 监控启动负载
1 #!/bin/bash
2 case $1 in
3 disk|DISK)
4 watch -n 1 "df -h"
5 ;;
6 memory|MEMORY)
7 watch -n 1 "free -h"
8 ;;
9 upload|UPLOAD)
10 watch -n 1 "uptime"
11 ;;
12 *)
13 echo Error
14 esac
六.expect
(一)问题脚本
vim /public/ask.sh
#!/bin/bash
read -p "what's your name:" NAME
read -p "How old are you: " AGE
read -p "Which objective: " OBJ
read -p "Are you ok? " OK
echo $NAME is $AGE\'s old study $OBJ feel $OK
(二)应答脚本
dnf install expect.x86_64 -y
1.这样写的弊端也暴露出来了,因此
2.再优化,让回答也变成变量
vim /public/answer.exp
1 #!/usr/bin/expect
2 set NAME [ lindex $argv 0]
3 set AGE [ lindex $argv 1]
4 set OBJ [ lindex $argv 2]
5 set OK [ lindex $argv 3]
6 set timeout 2
7 spawn sh /public/ask.sh
8 expect {
9 "name:" { send "$NAME\r";exp_continue}
10 "old" { send "$AGE\r";exp_continue}
11 "objective" { send "$OBJ\r";exp_continue}
12 "ok" { send "$OK\r"}
13 }
14 expect eof
3.也可以结合多行录入功能和函数调用,将问答脚本也写成.sh 结尾的
vim /public/answer.sh
1 #!/bin/bash
2 EXPECT()
3 {
4 /usr/bin/expect <<EOF
5 spawn sh /public/ask.sh
6 expect {
7 "name:" { send "$1\r";exp_continue}
8 "old" { send "$2\r";exp_continue}
9 "objective" { send "$3\r";exp_continue}
10 "ok" { send "$4\r"}
11 }
12 expect eof
13 EOF
14 }
15 EXPECT $1 $2 $3 $4
批量处理脚本
检测1…10主机,并抓取所有主机的值机名称和ip的对应列表,把列表保存在/mnt/dns_list文件中
七.break,continue,exit
contiue ##终止当此次前循环提前进入下个循环
break ##终止当前所在语句所有动作进行语句外的其他动作
exit ##脚本退出