linux expect 读取文件循环,linux expect的for和while循环以及if else 用法总结

linux 的expect是一个很强大的脚本工具,可以帮助我们执行很多自动化交互动作,是一个非常实用的脚本类工具。

关于expect的基本功能和用法请看我的上一篇文章:

这篇文章对expect的基本的命令做了一个基本的介绍,对于判断和循环的语法没有做过多介绍,本文着重讲一下expect的if else 用法和for/while循环的用法。

循环详解

我们通过以下例子来了解下expect的循环的用法,大家可以慢慢理解

#!/usr/bin/expect --forBob testing

#

puts"---1---"

for {set i 0} {$i < 10} {incr i} {

puts"I inside first loop: $i"}

puts"---2---"

for {set i 3} {$i < 2} {incr i} {

puts"I inside second loop: $i"}

puts"---3---"puts"Start"set i0

while {$i < 10} {

puts"I inside third loop: $i"incr i

puts"I after incr: $i"}

set i0incr i

puts"---4---"puts"$i"# This is equivalent to:

set i [expr {$i + 1}] #expect里的加减法

puts"---5---"puts"$i"运行结果

---1---I inside first loop:0I inside first loop:1I inside first loop:2I inside first loop:3I inside first loop:4I inside first loop:5I inside first loop:6I inside first loop:7I inside first loop:8I inside first loop:9

---2---

---3---Start

I inside third loop:0I after incr:1I inside third loop:1I after incr:2I inside third loop:2I after incr:3I inside third loop:3I after incr:4I inside third loop:4I after incr:5I inside third loop:5I after incr:6I inside third loop:6I after incr:7I inside third loop:7I after incr:8I inside third loop:8I after incr:9I inside third loop:9I after incr:10

---4---

1

---5---

2

if 和 else的用法expect中的判断语句:

if{ condition } {

#doyour things

} elseif {

#doyour things

}else{

#doyour things

}

expect中没有小括号(),所有的if/else, while, for的条件全部使用大括号{}, 并且{ 与左边要有空格,否则会报错。另,else 不能单独占一行,否则会报错。字符串比较

if { "$node" == "apple"} {

puts"apple"} elseif {"$node" == "other"} {

puts"invalid name"exit70}else{

puts"asd"}

对比string,使用==表示相等, !=标示不相等。switch 语句

switch $location {"apple" { puts "apple"}"banana" { puts "banana"}

default {

puts"other"}

}

记得左大括号{ 的左边要有空格,否则会报错读取用户输入

expect_user -re "(.*)\n"send_user"$expect_out(1, string)\n"

expect_user -re 表示正则表达式匹配用户按下回车前输入的所有字符

expect_out(1, string) 表示第一个匹配的内容,即回车前所有字符

expect_out(buffer) 所有的buffer内容break && continue

如c中一样,expect一样可以使用break && continue, 并且功能相同。

注:只能用在循环中。定义交互命令

# stick control + z invariable

set ControlZ \032# stick control+ c invariable

set ControlC \x03

# definestring embedded ctrl-z &&tab

set oddword foo\032bar\tgorpexpect读取文件的例子

#!/usr/bin/expect

# http://www.waitig.com

#open a fileset fd [open"/home/xiabao/myfile.txt"r]

set number0# read each linewhile { [gets $fd line] >= 0} { incr number }

puts"Number of lines: $number"close $fd

点赞 (11)赏分享 (0)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值