shell 的here document 用法、输入/输出重定向
见:https://my.oschina.net/u/1032146/blog/146941#OSC_h3_3、 http://www.runoob.com/linux/linux-shell-io-redirections.html 什么是Here DocumentHere Document 是在Linux Shell 中的一种特殊的重定向方式,它的基本的形式如下 cmd << delimiter Here Document Content delimiter
它的作用就是将两个delimiter之间的内容(Here Document Content部分) 传递给cmd 作为输入参数。 比如在终端中输入 fish@mangos:~$ cat << EOF > First Line > Second > Third EOF > EOF First Second Third EOF
注: 这里要注意几点
Here Document 不仅可以在终端上使用,在shell 文件中也可以使用,例如下面的here.sh 文件 cat << EOF > output.shecho "hello""world" EOF
使用
实例在命令行中通过 wc -l 命令计算 Here Document 的行数: $ wc -l << EOF 欢迎来到 菜鸟教程 www.runoobcom EOF 3 # 输出结果为 3 行 $ 我们也可以将 Here Document 用在脚本中,例如: #!/bin/bash # author:菜鸟教程# url:www.runoob.com cat EOF wwwcom EOF 执行以上脚本,输出结果: com
/dev/null 文件如果希望执行某个命令,但又不希望在屏幕上显示输出结果,那么可以将输出重定向到 /dev/null: $ command > /dev/null /dev/null 是一个特殊的文件,写入到它的内容都会被丢弃;如果尝试从该文件读取内容,那么什么也读不到。但是 /dev/null 文件非常有用,将命令的输出重定向到它,会起到"禁止输出"的效果。 如果希望屏蔽 stdout 和 stderr,可以这样写: null 2>&1
Here Document的变形delimiter 与变量在Here Document 的内容中,不仅可以包括普通的字符,还可以在里面使用变量,例如将上面的here.sh 改为 "This is output" $1sh here.sh HereDocument运行脚本得到output.sh的内容
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |