shell之免交互(Here Document、Expect)详解

本文详细介绍了Shell中的Here Document概念,包括免交互使用、变量设定、格式控制和多行注释。同时,讲解了 Expect工具的安装、基本命令、语法及执行方式,特别讨论了如何通过Expect解决shell脚本的交互问题,以及在创建用户和SSH免密登录等实际案例中的应用。
摘要由CSDN通过智能技术生成

1、Here Document概述

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


标记
■ Here Document使用注意事项
● 标记可以使用任意合法字符
● 结尾的标记一定要顶格写, 前面不能有任何字符
● 结尾的标记后面也不能有任何字符(包括空格)
● 开头标记前后的空格会被省略掉

1.1、Here Document免交互

■ 通过read命令接收输入并打印

[root@localhost ~]# vim here_non_interactive_read.sh  
#!/bin/bash  
read i <<EOF 
Hi  
EOF  
echo $i  
[root@localhost ~]# chmod +X here_non_interactive_read.sh  
[root@localhost ~]# ./here_non_interactive_read.sh  
[root@localhost ~]# Hi

■ 通过passwd给用户设置密码

[root@localhost ~]# vim here_non_interactive_passwd.sh   
#!/bin/bash   
passwd tom <<EOF   
This_ is_ password   
This_ is_ password   
EOF   
[root@localhost ~]# chmod +x here_ non_interactive_passwd.sh   
[root@localhost ~]# ./here_non_interactive_passwd.sh   
[root@localhost ~]#

1.2、Here Document变量设定

■ 变量替换

[root@localhost ~]# vim here_var_replace.sh
#!/bin/bash
doc_file="2019.txt"
i="company"
cat> $doc_ file << HERE
Take him from home to $i
HERE
[root@localhost ~]# chmod +x here_var_replace.sh
[root@localhost ~]# ./here_var_replace.sh
[root@localhost ~]# cat 2019.txt
Take him from home to company

■ 变量设定

[root@localhost ~]# vim here_var_set.sh
#!/bin/bash
ivar="Great! Beautyful!"
myvar=$(cat <<EOF
This is Line 1.
That are Sun,Moon and Stars.
$ivar
EOF
)
echo $myvar
[root@localhost ~]# sh here_var_set.sh
This is Line 1. That are Sun,Moon and Stars. Great<
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值