shell脚本快速入门之-----Here document使用方法总结

时间:2022-07-24
本文章向大家介绍shell脚本快速入门之-----Here document使用方法总结,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一、什么是Here Document

Here Document也被称为here-document/here-text/heredoc/hereis/here-string/here-script,在Linux/Unix中的shell中被广泛地应用,尤其在于用于传入多行分割参数给执行命令。除了shell(包含sh/csh/tcsh/ksh/bash/zsh等),这种方式的功能也影响和很多其他语言诸如Perl,PHP以及Ruby等。这篇文章以bash为例进行使用说明。

二、使用方式&限制

1、使用格式如下所示:

命令 << 分隔串(最为常见的为EOF)
字符串1
…
字符串n
分隔串

2、使用限制

分割串常见的为EOF,但不一定固定为EOF,可以使用开发者自行定义的,比如LIUMIAO
缺省方式下第二个分割串(EOF)必须顶格写,前后均不可有空格或者tab
缺省方式下第一个分割串(EOF)前后均可有空格或者tab,运行时会自动剔除,不会造成影响

3、使用示例

liumiaocn:~ liumiao$ cat << LIUMIAO
> hello
> world
> LIUMIAO
hello
world
liumiaocn:~ liumiao$

4、交互式的命令行

这个场景的说明可能比较绕口,但是一旦涉及实际的使用例子就会非常清晰。

交互式的命令行:比如sftp或者oracle的sqlplus,或者mysql的命令控制台,以sftp为例子,当我们输入sftp 用户名@sftp服务器登录之后,需要在sftp>的提示下进行各种sftp命令的操作。 多行输入:在sftp登录之后,如果希望进行(确认当前目录=>确认文件aa是否存在=>下载aa文件)操作的话,这需要按顺序执行pwd=>ls aa=>get aa三条命令。 转化为batch方式:很多时候上述的sftp命令可能是应用处理到某个时点被自动触发,这种人工逐行输入命令的方式不再适合。 上述实际操作示例如下:

liumiaocn:~ liumiao$ sftp root@host131
Connected to root@host131.
sftp> pwd
Remote working directory: /root
sftp> ls
aa                anaconda-ks.cfg   
sftp> get aa
Fetching /root/aa to aa
/root/aa                                                                                                             100%    9     0.7KB/s   00:00    
sftp> exit
liumiaocn:~ liumiao$ cat aa
aa infor
liumiaocn:~ liumiao$

可以看到,用户操作时需要输入密码,然后需要分别输入三条命令,如果希望一次执行完毕,可以使用如下Here Document方式

liumiaocn:~ liumiao$ sftp root@host131 <<EOF
> pwd
> ls
> get aa
> exit
> EOF
Connected to root@host131.
sftp> pwd
Remote working directory: /root
sftp> ls
aa                  anaconda-ks.cfg     
sftp> get aa
Fetching /root/aa to aa
/root/aa                                                                                                             100%    9     7.6KB/s   00:00    
sftp> exit
liumiaocn:~ liumiao$

三、使用技巧:<<- 与 <<的区别

使用<<-代替<<唯一的作用在与分割串所扩起来的内容,顶格的tab会被删除,用于ident。注意看一下如下的例子和执行结果,在hello和world前后加上tab和space,用于确认结果。

liumiaocn:~ liumiao$ cat testhere.sh 
#!/bin/sh

echo "## test space with <<-"
cat <<- EOF
  hello
  	world
EOF

echo "## test space with <<-"
cat <<- EOF
hello  
world  
EOF

echo "## test tab with <<- "
cat <<- EOF
	hello
	world
EOF

echo "## test tab with <<- "
cat <<- EOF
hello	
world	
EOF
liumiaocn:~ liumiao$ 

执行结果如下所示

liumiaocn:~ liumiao$ sh testhere.sh 
## test space with <<-
  hello
  	world
## test space with <<-
hello  
world  
## test tab with <<- 
hello
world
## test tab with <<- 
hello	
world	
liumiaocn:~ liumiao$ 

可以看到唯一起作用的是第三个例子,顶格的tab没有被显示(由于space和tab的信息显示清楚,请读者自行验证和确认)