(cat<<EOF)不使用反斜杠转义的技巧
转自:https://blog.51cto.com/xiaozhenkai/2608853
在分界符EOF前添加反斜杠\,或者用单引号、双引号括起来:
cat >> a.sh << \EOF
echo `hostname`
echo $HOME
EOF
cat >> a.sh << "EOF"
echo `hostname`
echo $HOME
EOF
cat >> a.sh << 'EOF'
echo `hostname`
echo $HOME
EOF
linux重定向多个文件,shell 多行重定向方法(多重嵌套)
转自:https://blog.csdn.net/weixin_33630090/article/details/116578005
这里讲的是多重嵌套。没用过 eof的朋友请参考其他基础贴
在自动化运维中,常常需要shell脚本。在自动化创建脚本时,会遇到脚本内容里有用eof重定向到配置文件的代码。
这样就不能用eof来创建脚本了,所以要多方法混用来实现自动化。
重定向方法1:
cat > /tmp/123.txt << eof
this is line 1 of the message.
this is line 2 of the message.
this is line 3 of the message.
this is line 4 of the message.
this is the last line of the message.
eof
**重定向方法2:**参考,有更多高级用法,纯英文网站,我目前双层嵌套就够用了。所以没多看。
cat > /tmp/123.txt << endofmessage
this is line 1 of the message.
this is line 2 of the message.
this is line 3 of the message.
this is line 4 of the message.
this is the last line of the message.
endofmessage
嵌套方法为:
cat > /server/scripts/test2.sh << endofmessage
cat >>/etc/sysctl.conf<
net.core.wmem_default = 8388608
net.core.rmem_default = 8388608
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
eof
endofmessage
这样就创建了一个含有eof的脚本
注:endofmessage为自定义字符
含全局变量的嵌套写法
#!/bin/bash
iplist_B_VIP=192.168.1.2
sh_dir=/tmp
cat > $sh_dir/1.sh << ENDOFEOF
#!/bin/bash
rm -f /tmp/a.sh
## \EOF:EOF前面加斜杠为脚本内容不转义
cat >> /tmp/a.sh << \EOF
#!/bin/bash
echo_cmd="aaaa"
## 由于外面一层输入需要转义,因此这边要加斜杠
echo \$echo_cmd
EOF
## 要引用全局变量,因此,这边不需要转移
B_Vip=$iplist_B_VIP
if [ \`ip -4 addr | grep inet | grep "\${B_Vip}/" | wc -l\` == 1 ];then
echo aaa
[ \$? != 0 ] && echo "Failed......" || echo "successful."
fi
ENDOFEOF
sh /tmp/a.sh
0