Shell----免交互
一、Here Document
1、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等。
2、Here Document用法
<<符号也被称为Here Document,代表你需要的内容在这里的意思。
当shell看到<<的时候,它就会知道下一个词是一个分界符。在该分界符以后的内容都被当作输入,直到shell又看到该分界符(位于单独的一行)。这个分界符可以是你所定义的任何字符串,但一般习惯EOF
命令 <<标记
...
...
...
标记
3、Here Document参数
标记可以使用任意合法字符
结尾的标语一定要顶格写,前面不能有任何字符
结尾的标记后面也不能有任何字符(包括空格)
开头标记前后的空格会被省略
4、实例
1、给用户创建密码
[root@localhost ~]# passwd zhangsan <<EOF
> 123
> 123
> EOF
更改用户 zhangsan 的密码 。
新的 密码:无效的密码: 密码少于 8 个字符
重新输入新的 密码:passwd:所有的身份验证令牌已经成功更新。
2、创建yum源
[root@localhost ~]# cat > test.repo <<EOF
> [test]
> name=test
> baseurl=file:///mnt
> enabled=1
> gpgcheck=0
> EOF
[root@localhost ~]# cat test.repo
[test]
name=test
baseurl=file:///mnt
enabled=1
gpgcheck=0
3、创建脚本,非交互给磁盘分区格式化
#!/bin/bash
fdisk /dev/sdb << -EOF
n
p
w
EOF
4、挂载光盘
[root@localhost ~]# cat >yum.repo <<EOF
> [test]
> name=test
> baseurl=file:///mnt
> enabled=1
> gpgcheck=0
> EOF
[root@localhost ~]# cat yum.repo
[test]
name=test
baseurl=file:///mnt
enabled=1
gpgcheck=0
一般是对于多行,写入一个文件,避免免交互
对文件进行操作:
[root@localhost ~]# cat > yum.repo <<EOF
> hello
> EOF
[root@localhost ~]# cat yum.repo
hello
//会覆盖之前的内容
[root@localhost ~]# cat >> yum.repo <<EOF
> hello
> world
> EOF
使用追加
[root@localhost ~]# cat yum.repo
hello
hello
world