一.for语句
1.for 语句的结构
for var in item1 item2 ... itemN
do
command1
command2
...
commandN
done
2.for语句的循环设置
`for NUM in 1 2 3 == for NUM in {1..3} == for NUM in seq 1 3
in与seq的区别在seq更高级,可以设置步长,如seq 1 2 5(设置1-5之间的步长为
举例:编写一个脚本,后边跟上用户名文件和密码文件,建立用户!
#!/bin/bash
MAX_LINE=`wc -l $1 | cut -d " " -f 1`
for LINE_NUM in `seq 1 $MAX_LINE`
do
USERNAME=`sed -n "${LINE_NUM}p" $1`
PASSWORD=`sed -n "${LINE_NUM}p" $2`
useradd $USERNAME
echo $PASSWORD | passwd --stdin $USERNAME
done
二.while 语句
while循环用于不断执行一系列命令,也用于从输入文件中读取数据;命令通常为测试条件。其格式为:
while condition
do
command
done
until 循环
until 循环执行一系列命令直至条件为 true 时停止。
until 循环与 while 循环在处理方式上刚好相反。
一般 while 循环优于 until 循环,但在某些时候—也只是极少数情况下,until 循环更加有用。
until 语法格式:
until condition
do
command
done
三.if语句
if 语句语法格式:
if condition
then
command1
command2
...
commandN
fi
if else 语法格式:
if condition
then
command1
command2
...
commandN
else
command
fi
if else-if else 语法格式:
if condition1
then
command1
elif condition2
then
command2
else
commandN
fi
四.case语句
Shell case语句为多选择语句。可以用case语句匹配一个值与一个模式,如果匹配成功,执行相匹配的命令。case语句格式如下:
case 值 in
模式1)
command1
command2
...
commandN
;;
模式2)
command1
command2
...
commandN
;;
esac
五.expect
expect 是自动应答命令用于交互式命令的自动执行 spawn 是expect中的监控程序,其运行后会监控命令提出的交互问题
send 发送问题答案给交互命令
exp_continue 表示当问题不存在时继续回答下面的问题
expecte of 表示问题回答完毕退出expect环境
interact 表示问题回答完毕留在交互界面
set NAME [ lindex $argvn ] 定义变量
expect示例1.:
vim ask.sh
#!/bin/bash
read -p "what's your name: " NAME
read -p "How old are you: " AGE
read -p "Which class you study: " CLASS
read -p "You feel happy or terrible ?" FEEL
echo $NAME is $AGE\'s old and $NAME is feel $FEEL
chmod +x ask.sh
vim ans.sh
#!/bin/bash
expect <<EOF
spawn ask.sh 问题所在的脚本
expect {
name { send "jay\r" ; exp_continue} exp_continue 表示当问题不存在时继续回答下面的问题
old {send "18\r" ; exp_continue}
study { send "music\r" ; exp_continue }
feel { send "happy\r"}
}
expect eof expect eof 表示问题回答完毕退出expect环境
EOF
sh ans.sh
跳出循环
在循环过程中,有时候需要在未达到循环结束条件时强制跳出循环,Shell使用两个命令来实现该功能:break和continue。
break命令
break命令允许跳出所有循环(终止执行后面的所有循环)。
continue
continue命令与break命令类似,只有一点差别,它不会跳出所有循环,仅仅跳出当前循环。