shell编程中变量的应用:for,while,case,expect,if语句

一.for语句

1.for 语句的结构

for 
do
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 条件
do
done

三.if语句

if     条件1
then   语句1
elif   条件2
then   语句2
...
else   剩余条件
fi

四.case语句

case
 word1 )
  action1
  ;;
 word2)
  action2
  ;;
 *)
  action_last
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

猜你喜欢

转载自blog.csdn.net/jay_youth/article/details/80816308