Shell编程----Expect免交互&标记法免交互
文章目录
前言
一: Here Document 免交互
1.1:什么是Here Document?
- Here document (here-document, here-text, heredoc, hereis, here-string, here-script)是一个文件文字或输入流文字:它是源代码文件的一部分,被视为它是一个单独的文件。该术语还用于使用类似语法,保留换行符和文本中的其他空格(包括缩进)的多行字符串文字形式。
1.2: Here Document 概述
-
使用I/O重定向的方式将命令列表提供给交互程序
-
标准输入的一种替代品
-
语法格式
命令 <<标记 ... ... 标记
1.3: Here Document 使用注意事项
- 标记可以使用任意合法字符
- 结尾的标记一定要顶格写,前面不能有任何字符
- 结尾的标记后面也不能有任何字符(包括空格)
- 开头标记前后的空格会被省略掉
1.4: Here Document免交互
-
通过read 命令接受输入并打印
[root@shell ~]# vim b.sh #!/bin/bash read i <<EOF hello world my name is zhangsan EOF echo $i [root@shell ~]# chmod +x b.sh [root@shell ~]# ./b.sh hello world
-
通过paswd给用户设置密码
[root@shell ~]# vim passwd.sh #!/bin/bash useradd zhangsan passwd zhangsan <<EOF abc123 abc123 EOF [root@shell ~]# chmod +x passwd.sh [root@shell ~]# ./passwd.sh 更改用户 zhangsan 的密码 。 新的 密码:无效的密码: 密码少于 7 个字符 重新输入新的 密码:passwd:所有的身份验证令牌已经成功更新。
1.5: Here Document 变量设定
-
变量替换
[root@shell ~]# vim filename.sh #!/bin/bash filename="test.txt" school="kgc" cat > $filename <<EOF this is $school .com EOF [root@shell ~]# chmod +x filename.sh [root@shell ~]# ./filename.sh [root@shell ~]# ls test.txt ..... [root@shell ~]# cat test.txt this is kgc .com
-
变量设定
[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! Beautyful!
1.6: Here Document 格式控制
-
关闭变量替换功能
[root@localhost ~]# cat here_format_shut.sh #!/bin/bash cat <<'EOF' #单引号关闭变量替换 This is Line 1. $kgc EOF [root@localhost ~]# sh here_format_shut.sh This is Line 1. $kgc #变量当成普通字符输出
-
去除每行之前的TAB字符
[root@localhost ~]# vim here_format_tab.sh #!/bin/bash cat <<-