Bash EOF 技巧
EOF适用场景:
- 命令行多行输出
- 脚本包装
- 类型配置文件
1. 命令行输出
$ cat << EOF
> Hello
> EOF
Hello
- 1
- 2
- 3
- 4
2. 写入文本
cat << EOF >1.txt
111
222
333
EOF
- 1
- 2
- 3
- 4
- 5
复制终端是这样的。
cat << EOF >1.txt
> 111
> 222
> 333
> EOF
- 1
- 2
- 3
- 4
- 5
回车后
$ cat 1.txt
111
222
333
- 1
- 2
- 3
- 4
3. 追加文本
cat << EOF >> 1.txt
444
555
666
EOF
- 1
- 2
- 3
- 4
- 5
查看1.txt内容
$ cat 1.txt
111
222
333
444
555
666
- 1
- 2
- 3
- 4
- 5
- 6
- 7
4. 覆盖文本
cat << EOF >1.txt
aaa
bbb
ccc
EOF
- 1
- 2
- 3
- 4
- 5
查看
$ cat 1.txt
aaa
bbb
ccc
- 1
- 2
- 3
- 4
5. 自定义 EOF
cat << a > 1.txt
111
222
333
a
- 1
- 2
- 3
- 4
- 5
输出:
$ cat 1.txt
111
222
333
- 1
- 2
- 3
- 4
6. 另一种格式
cat > filename <<EOF
cat << EOF > filename
cat > 1.txt <<EOF
123
456
789
EOF
- 1
- 2
- 3
- 4
- 5
查看
$ cat 1.txt
123
456
789
- 1
- 2
- 3
- 4
追加内容
cat >> 1.txt <<EOF
abc
def
ghi
EOF
- 1
- 2
- 3
- 4
- 5
查看内容
$ cat 1.txt
123
456
789
abc
def
ghi
- 1
- 2
- 3
- 4
- 5
- 6
- 7
7. 示例
7.1 配置文件
或者cat << EOF > /usr/local/mysql/my.cnf
cat > /usr/local/mysql/my.cnf << EOF
[client]
port = 3306
socket = /usr/local/mysql/var/mysql.sock
[mysqld]
port = 3306
socket = /usr/local/mysql/var/mysql.sock
basedir = /usr/local/mysql/
datadir = /data/mysql/data
pid-file = /data/mysql/data/mysql.pid
user = mysql
bind-address = 0.0.0.0
server-id = 1
sync_binlog=1
log_bin = mysql-bin
[myisamchk]
key_buffer_size = 8M
sort_buffer_size = 8M
read_buffer = 4M
write_buffer = 4M
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
port = 3306
EOF
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
7.2 新建分区并挂载
$ cat auto_add_disk.sh
#!/bin/bash
fdisk /dev/sdb <<EOF
n
p
1
wq
EOF
/sbin/mkfs .ext4 /dev/sdb1 && /bin/mkdir -p /data && /bin/mount /dev/sdb1 /data
echo 'LABEL=data_disk /data ext4 defaults 0 2' >> /etc/fstab
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
7.3 设置变量
$ sql=$(cat <<EOF
SELECT foo, bar FROM db
WHERE foo='baz'
EOF
)
$ echo -e "$sql"
- 1
- 2
- 3
- 4
- 5
- 6
- 7
7.4 输出脚本
cat <<EOF > print.sh
#!/bin/bash
echo \$PWD
echo $PWD
EOF
- 1
- 2
- 3
- 4
- 5
查看内容
$ cat print.sh
#!/bin/bash
echo $PWD
echo /home/user
- 1
- 2
- 3
- 4
7.5 匹配输出
$ cat <<EOF | grep 'b' | tee b.txt
> foo
> bar
> baz
> EOF
bar
baz
$ cat b.txt
bar
baz
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
7.6 json 文本
cat >> /etc/docker/daemon.json < EOF
{
"exec-opts": ["native.cgroupdriver=systemd"],
"log-driver": "json-file",
"log-opts": {
"max-size": "100m"
},
"registry-mirrors": [
"https://hub-mirror.c.163.com",
"https://mirror.baidubce.com"
]
}
EOF
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
查看
$ cat /etc/docker/daemon.json
{
"exec-opts": ["native.cgroupdriver=systemd"],
"log-driver": "json-file",
"log-opts": {
"max-size": "100m"
},
"registry-mirrors": [
"https://hub-mirror.c.163.com",
"https://mirror.baidubce.com"
]
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
参考: