for NUM in 1 2 3 ## 1 2 3 分别赋给变量NUM
for NUM in {1..3} ##1..3所有的数分别赋给变量NUM
for NUM in `seq 1 3` 或者 for NUM in `seq 1 2 10` ##for NUM in `seq 1 2 10`设置循环步长为2。
do
可执行的语句
done
vim test.sh
#!/bin/bash
for NUM in 1 2 3
do
echo $NUM
done
vim test.sh
#!/bin/bash
for NUM in `seq 1 2 10`
do
echo $NUM
done
while 条件 | until 条件 ##条件为真,则执行循环语句|直到条件为假,否则一直执行
do
循环语句
done
vim test
#!/bin/bash
while true ##while 当条件为真则执行,这里true默认一直循环
do
read -p "Please input a word: " WORD
while [ "$WORD" = "exit" ] ##while用户输入为exit是则输出bye并且退出脚本。
do
echo bye
exit
done
echo $WORD
done
#!/bin/bash
until false
do
read -p "Please input a word: " WORD
while [ "$WORD" = "exit" ]
do
echo bye
exit
done
echo $WORD
done
if 条件一 ##如果条件一满足,执行语句一。如果条件二满足,执行语句二。如果都不满足,执行语句n
then 语句一
elif 条件二
then 语句二
。。。
else
语句n
fi
if语句示例:
vim test.sh
#!/bin/bash
if
[ "$1" = "a" ]
then
echo apache
elif
[ "$1" = "b" ]
then
echo backup
elif [ "$1" = "c" ]
then
echo chronyd
else
echo "Don't no"
fi
case 变量 in ##变量的值如果为word1,则执行action1。如果为word2,则执行action2,都不满足则执行action3。
word1)
action1
;;
word2)
action2
;;
*)
action3
esac
vim test.sh
#!/bin/bash
case $1 in
a)
echo apache
;;
b)
echo backup
;;
c)
echo chronyd
;;
*)
echo "error: input a or b or c!!!"
esac
expect 是自动应答命令用于交互式命令的自动执行
spawn 是 expect 中的监控程序,其运行后会监控命令提出的
交互问题
send 发送问题答案给交互命令
"\r" 表示回车
exp_continue 标示当问题不存在时继续回答下面的问题
expect eof 标示问题回答完毕退出 expect 环境
interact 标示问题回答完毕留在交互界面
set NAME [ lindex $argv n ] 定义变量
示例:
首先:
下载expect软件:
先写一个需要键入信息的简单脚本:
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 auto_ask.sh
#!/bin/bash
expect <
vim auto_ask.sh
#!/bin/bash ##脚本环境为/bin/bash
expect <
vim auto_ask.sh
#!/usr/bin/expect
set NAME [ lindex $argv 0 ] ##类似于/bin/bash环境中的$1
set AGE [ lindex $argv 1 ] ##类似于/bin/bash环境中的$2
set OBJ [ lindex $argv 2 ] ##类似于/bin/bash环境中的$3
set FEEL [ lindex $argv 3 ] ##类似于/bin/bash环境中的$4
spawn /mnt/ask.sh
expect {
"name" { send "$NAME\r" ; exp_continue }
"old" { send "$AGE\r" ; exp_continue }
"study" { send "$OBJ\r" ; exp_continue }
"feel" { send "$FEEL\r" }
}
expect eof
exit n 脚本退出,退出值为 n
break 退出当前循环
continue 提前结束循环内部的命令,但不终止循环
1、exit
#!/bin/bash
echo "study linux!!!"
exit 66
vim test.sh
#!/bin/bash
for i in `seq 0 2 8`
do
echo $i
[ "$i" = "4" ] && {
break
}
done
vim test.sh
#!/bin/bash
for i in `seq 0 2 8`
do
[ "$i" = "4" ] && {
continue
} || {
echo $i
}
done