1. for
- 格式
- for 定义变量
- do 使用变量,执行动作
- done 结束标志
- 格式1:
- #!/bin/bash
- for WESTOS in `seq 1 2 10` ##表示从1到10,步长为2
- do
- echo $WESTOS
- done
- 格式2:
- for WESTOS in 1 2 3
- do
- echo $WESTOS
- done
- 格式3:
- for n in {10..1} ##倒叙排
- do
- echo $WESTOS
- done
- 格式4:
- for ((n=0;n<10;n++))
- do
- echo $WESTOS
- done
- 脚本练习:
- check_host.sh
- 用此脚本检测10台与您当前主机直连主机是否网络通常
- 如果网络通常请显示主机的ip列表
2. while
- while ture #条件为真
- do #条件成立所作循环动作
- done
3. until
- until false ##条件为假
- do #条件不成立所作循环动作
- done
4. if
- if
- then
- elif
- then
- ...
- else
- fi
- 脚本练习:
- check_file.sh
- please input filename: file
- file is not exist
- file is file
- file is direcory
- 此脚本会一直询问直到用户输入exit为止
之前输入westos显示Linux的题用if循环写
脚本练习
5. case
- 格式
- case $1 in
- word1|WORD1)
- action1 ##动作1
- ;;
- word2|WORD2)
- action2 ##动作2
- ;;
- *)
- action3 ##动作3
- esac
- 1. 脚本示例(输入westos,显示linux,输入linux显示westos,输入其他显示unkow)
- 2. 脚本练习
- system_watch.sh disk memory upload (每秒显示)
- disk 监控磁盘使用情况
- memory 监控内存使用情况
- upload 监控启动负载
-
脚本示例
-
脚本练习
6. expect
- 问题脚本(.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
- 应答脚本(.exp)
- 做法一:
- #!/usr/bin/expect
- spawn sh /root/Desktop/wenti.sh
- expect {
- "name" { send "lee\r";exp_continue }
- "old" { send "18\r";exp_continue }
- "subject" { send "linux\r";exp_continue }
- "ok" { send "okk\r" }
- }
- expect eof
- 做法二:
- #!/usr/bin/expect
- set timeout 1
- set NAME [ lindex $argv 0 ]
- set AGE [ lindex $argv 1 ]
- set OBJ [ lindex $argv 2 ]
- set FEEL [ lindex $argv 3 ]
- spawn /mnt/ask.sh
- expect {
- "name" { send "$NAME\r";exp_continue }
- "old" { send "$AGE\r";exp_continue }
- "objective" { send "$OBJ\r";exp_continue }
- "ok" { send "$FEEL\r" }
- }
- expect eof
-
- 做法三:
- #!/bin/bash
- EXPECT()
- {
- /usr/bin/expect <<EOF
- spawn sh /root/Desktop/wenti.sh
- expect {
- "name:" { send "$1\r";exp_continue }
- "old:" { send "$2\r";exp_continue }
- "subject:" { send "$3\r";exp_continue }
- "ok:" { send "$4\r" }
- }
- expect eof
- EOF
- }
- EXPECT $1 $2 $3 $4
- 脚本练习(dns_list.sh)
- 获取与自己主机直连的1-10台主机主机名并存到文件中
-
-
-
-
示例
问题脚本
应答脚本
做法一:做法二:
脚本练习
7. break continue exit
- contiue ##终止当此次前循环提前进入下个循环
- break ##终止当前所在语句所有动作进行语句外的其他动作
- exit ##脚本退出