shell编程教学(五) |必备知识---- 交互式 | 函数块 (二)

一、交互式(编程时相当常用)

交互即人与电脑交流,其精密程度直接影响用户体验!

1、read -p
格式:

 read -p "此处为要显示的内容" WESTOS         
 						    ##read -p "xxxxx" 变量名
							##变量名任取,变量值为交互时输入的内容
							##""内的xxxxx是交互时显示的内容
							##在变量名前加 -s 能隐藏交互时输入的内容

示例:(最好能跟着敲一边,就能理解了!)

[root@allen mnt]# read -p "who are you ? "  WESTOS    ##WESTOS为变量
who are you ? linux					  ##who are you ?是交互时显示的内容,linux是我输入的
[root@allen mnt]# echo $WESTOS		  ##打印变量WESTOS的值
linux								  ##其值为我输入的值,linux
[root@allen mnt]# read -p "who are you ? " -s  WESTOS
who are you ? 							##隐藏了我输入的值 allen
[root@allen mnt]# echo $WESTOS
allen
[root@allen mnt]# 

在这里插入图片描述
2、expect

expect 是自动应答命令,用于交互式命令的自动执行,其特点是关键字匹配回答对应内容

1)安装软件

[root@allen ~]# yum install expect -y      ##安装expect

2)编写一个脚本,这个脚本需要用户手动输入信息

[root@allen mnt]# vim question.sh
[root@allen mnt]# chmod +x /mnt/question.sh      ##加上可执行权限
[root@allen mnt]# cat question.sh 				 ##脚本内容
#!/bin/bash
read -p "who are you ?" NAME
read -p "how are you old ? " AGE
read -p "what's your gender ? " GENDER
echo "$NAME 是一个 $AGE 岁的 $GENDER !"

运行效果,中文均为交互时手动输入的信息
在这里插入图片描述
3)编写一个expect文件,去回答上一个脚本的问题

(主要学习如何编写expect脚本)

[root@allen mnt]# vim answer.exp
#!/usr/bin/expect							##注意解释器
spawn /mnt/question.sh				##监控要自动回答的文件(绝对路径)
expect{								## 自动回答函数
	who { send "李大大\r";exp_continue }     # who,old,gender均为要回答的脚本的交互
	old { send "21\r";exp_continue }		#内容关键字,可手动往上翻,自行对比
	gender { send "人妖\r" }					# send--发送问题答案,\r--换行
								##exp_continue表示当问题不存在时继续回答下面的问题
}
expect eof			# 表示回答完毕问题,退出expect环境

在这里插入图片描述
注意

1、使用expect时要下载工具yum install expect
2、expect不是脚本,不能使用脚本的那些命令
3、expect文件后缀为.exp,解释器为/usr/bin/expect
4、expect自动应答是关键字匹配的方式
5、执行expect文件方法是 expect answer.exp(文件名)

4)测试,展示自动回答

[root@allen mnt]# expect answer.exp

在这里插入图片描述

二、脚本中的函数块

脚本中的函数是把一个复杂的语句块定义成一个字符串的方法
合理的使用函数块可以极大的减少代码量,以及更易维护

本部分简单,只需要理解函数块的功能及其格式即可

格式如下:==

User_Add()                ##User_Add函数名,原则能体现其功能即可
{
####################
####  函数内容  ######
####################
}
User_Add	      		##调用User_Add	函数

示例:无限循环

脚本内容:

[root@allen mnt]# vim test.sh 
[root@allen mnt]# cat test.sh 
#!/bin/bash
Endless_Loop()		
{
read -p "who are you ?  " NAME
Endless_Loop						##调用Endless_Loop函数
}
Endless_Loop						##调用Endless_Loop函数
[root@allen mnt]# 

在这里插入图片描述
运行脚本:

[root@allen mnt]# sh test.sh 
who are you ?  root
who are you ?  root      ##无限循环
who are you ?  allen
who are you ?  root
who are you ?  

无限循环
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值