cat和EOF简介
cat 用于显示文本文件内容,全部输出
EOF “end of file”,表示文本结束符
用法1:多行内容导入到文件
cat eof.sh
#!/bin/bash
cat > 2.txt <<EOF
this is test eof
this is test eof2
this is test eof3
EOF
结果:
cat 2.txt
this is test eof
this is test eof2
this is test eof3
将this is test eof/this is test eof2/this is test eof3 这三行作为cat的输入,然后重定向到文件2.txt
用法2:文件追加
cat 2.txt
123
cat >>2.txt <<EOF
456
789
EOF
cat 2.txt
123
456
789
cat的多行内容有$等特殊字符时,须利用转义字符\
cat > file <<EOF
export ORACLE_SID=yqpt
export PATH=\$PATH:\$ORACLE_HOME/bin
EOF
说明:其实可以用其他字符来代替EOF,它也只是个标识符而已!
如果cat内容中带有 $变量的时候会将$和变量名变成空格,可以利用转义字符\添加之后可以搞定。
实现多行注释EOF
举例:
#!/bin/bash
echo "123"
:<<EOF
echo "test1" 【注释的行】
echo "test2" 【注释的行】
echo "test3" 【注释的行】
EOF
: 代表什么都不做,即达到注释的功能
什么是Here Document
Here Document 是在Linux Shell 中的一种特殊的重定向方式,它的基本的形式如下:
cmd << delimiter
Here Document Content
delimiter
它的作用就是将两个 delimiter 之间的内容(Here Document Content 部分) 传递给cmd 作为输入参数;
注:这里delimiter可以是任意的字符串,一般写成EOF
@1、EOF 只是一个标识而已,可以替换成任意的合法字符
@2、作为结尾的EOF一定要顶格写,前面不能有任何字符
@3、作为结尾的EOF后面也不能有任何的字符(包括空格)
@4、作为起始的EOF前后的空格会被省略掉
举例
例1
cat << EOF > output.sh
echo "hello"
echo "world"
EOF
将多行内容写入到output.sh脚本文件里
例2
$ wc -l << EOF
欢迎来到
菜鸟教程
www.runoob.com
EOF
3
Here Document的变形 与delimiter 与变量
1、Here Document的的变量替换
here.sh
#!/bin/bash
cat << EOF > output.sh
echo "This is output"
echo $1
EOF
执行:sh here.sh num1
cat output.sh 内容:
echo "This is output"
echo num1
这里变量$1被替换成num1
2、Here Document的的取消变量替换
here.sh
#!/bin/bash
cat << "EOF" > output.sh
echo "This is output"
echo $1
EOF
执行:sh here.sh num1
cat output.sh 内容:
echo "This is output"
echo $1
这里EOF被加上双引号或者单引号,即可取消变量的替换
3、Here Document前面加上 - 表示下述字段所有TAB键将全部忽略[不能是空格]
here.sh
#!/bin/bash
cat << -EOF
echo "This is output"
EOF
sh here.sh
结果:
echo "This is output" 【去掉了前面的tab键】
最后编辑于 :2019.01.11 23:04:20
©著作权归作者所有,转载或内容合作请联系作者 平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。