1.for语句
-
作用
为循环执行动作
-
for语句结构
for 定义变量
do 使用变量,执行动作
done 结束标志 -
for语句的基本格式
格式1:
#!/bin/bash
for WESTOS in $(seq 1 2 10)
do
echo $WESTOS
done
格式2:
for WESTOS in westos linux lee
do
echo $WESTOS
done
格式3:
for WESTOS in {10..1}
do
echo $WESTOS
done
格式4:
for ((WESTOS=0;WESTOS<10;WESTOS++))
do
echo $WESTOS
done
-
脚本练习:
check_host.sh
用此脚本检测10台与您当前主机直连主机是否网络通常
如果网络通常请显示主机的ip列表
2.条件语句
-
while…do语句
作用:
条件为真执行动作
语句结构
while ture
do
done
-
until…do 语句
作用:
条件为假执行动作
语句结构
until false
do
done
-
if…then…elif…then…else…fi 语句
作用:
多次判定条件执行动作
代码结构
if
then
elif
then
...
else
fi
-
脚本练习:
check_file.sh
please input filename: file
file is not exist
file is file
file is direcory
此脚本会一直询问直到用户输入exit为止
5.case
case $1 in
westos) #如果输入为westos
echo linux #输出为linux
;;
linux) #如果输入为linux
echo westos #输出westos
;;
*) #其余的情况
echo error #报错
esac #结束
6.expect
问题脚本
#!/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
应答脚本
#!/usr/bin/expect
set timeout 1
set NAME [ lindex $argv 0 ]
set AGE [ lindex $argv 1 ]
set OBJ [ lindex $argv 2 ]
set FEEL [ lindex KaTeX parse error: Expected '}', got 'EOF' at end of input: …name" { send "NAME\r";exp_continue }
“old” { send “KaTeX parse error: Can't use function '\r' in math mode at position 4: AGE\̲r̲";exp_continue …OBJ\r”;exp_continue }
“ok” { send “$FEEL\r” }
}
expect eof
脚本练习
host_list.sh
检测172.25.254.1-172.25.254.10网络是否开启
如果网络正常请生成解析列表hosts_list
格式如下
ip 主机名称
例如:172.25.254.1为开启状态主机名为westos_student1.westos.org
hosts_list中
172.25.254.1 westos_student1.westos.org
7.break,continue,exit
contiue ##终止当此次前循环提前进入下个循环
break ##终止当前所在语句所有动作进行语句外的其他动作
exit ##脚本退出