Shell脚本免交互

Here Document概述

使用I/O重定向的方式将命令列表提供给交互式程序
标准输入的一种替代品
格式:

命令 <<标记
...
...
标记
Here Document使用注意事项

1:标记可以使用任意合法字符
2:结尾的标记一定要顶格写,前面不能有任何字符
3:结尾的标记后面也不能有任何字符(包括空格)
4:开头标记前后的空格会被省略掉

Here Document免交互

[root@localhost ~]# vim test.sh
#!/bin/bash
read i <<EOF
hello
EOF
echo $i
[root@localhost ~]# bash test.sh
hello
[root@localhost ~]# vim test.sh
#!/bin/bash
useradd zhangsan
passwd zhangsan <<EOF
123123		#passwd命令需要的密码和确认密码
123123
EOF
[root@localhost ~]# bash test.sh

Here Document变量设定

变量替换
[root@localhost ~]# vim test.sh
#!/bin/bash
doc_file="test.txt"
cat>$doc_file<<EOF
this is test
EOF
[root@localhost ~]# bash test.sh
[root@localhost ~]# cat test.sh
this is test
[root@localhost ~]# vim test.sh
#!/bin/bash
doc_file="test.txt"
i="first"
cat>$doc_file<<EOF
this is $i test
EOF
[root@localhost ~]# bash test.sh
[root@localhost ~]# cat test.sh
this is first test
变量设定
[root@localhost ~]# vim test.sh
#!/bin/bash
doc_file="test.txt"
testfile=$(<<EOF
this is test
$doc_file
EOF
)
echo $testfile
[root@localhost ~]# bash test.sh
this is first test test.txt

Here Document格式控制

关闭变量替换功能
[root@localhost ~]# vim test.sh
#!/bin/bash
cat<<'EOF'		===>单引号关闭变量替换
This is test.
$text
EOF
[root@localhost ~]# bash test.sh
This is test.
$text
去除每行之前的TAB字符
[root@localhost ~]# vim test.sh
#!/bin/bash
cat<<-'EOF'			===>'-'表示抑制行首的TAB作用
	This is test.
	$text
EOF
[root@localhost ~]# bash test.sh
This is test.
$text

Expect

建立在tcl之上的一个工具
用于进行自动化控制和测试
解决shell脚本中交互相关的问题
判断上次输出结果中是否包含指定的字符串,如果有则立即返回,否则就等待超时时间后返回
只能捕捉由spawn启动的进程的输出
用于接受命令执行后的输出,然后和期望的字符串匹配

send

向进程发送字符串,用于模拟用户的输入
该命令不能自动回车换行,一般要加\r(回车)

spawn ssh@20.0.0.20 追踪指令
expect “connecting (yes/no)?” 捕捉会话
send yes\r 自动发送指令—执行

结束符

expect eof 执行自动话任务通常使用expect eof​等待执行结束
interact 执行完成后保持交互状态,把控制权交给控制台

exp_continue

exp_continue ===>不跳过继续匹配
允许expect继续向下执行指定

接收参数

Expect脚本可以接受从bash传递的参数
可以使用[lindex $argv n]获得
n从0开始,分别表示第一个,第二个,第三个…参数
set 变量名(filename) [lindex $argv 0]

语法

单一分支语法

匹配的内容跟发送的内容需要加上双引号
expect “password:” {send “mypassword\r”;}

多分支模式语法
  1. expect “aaa” {send “AAA\r”}
    expect “bbb” {send “BBB\r”}
    expect “ccc” {send “CCC\r”} #send命令不具备回车换行功能,一般要加\r或\n
  2. expect {
    “aaa” {send “AAA\r”}
    “bbb” {send “BBB\r”}
    “ccc” {send “CCC\r”} #只要匹配了aaa或bbb或ccc中的任意一个,执行相应的send语句后退出该expecct语句
  3. expect {
    “aaa” {send “AAA\r”;exp_continue}
    “bbb” {send “BBB\r”;exp_continue}
    “ccc” {send “CCC\r”} #exp_continue表示继续后面的匹配,如果匹配了aaa,执行完send语句后还要继续向下匹配bbb
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值