如何使用此处文档在bash脚本中将数据写入文件
时间:2020-01-09 10:44:03 来源:igfitidea点击:
如何在Bash Shell脚本中使用Heredoc重定向功能(此处为文档)将数据写入文件?
这里的文档不过是I/O重定向,它告诉bash shell从当前源读取输入,直到看到仅包含定界符的行。
这对于为ftp,cat,echo,ssh和许多其他有用的Linux/Unix命令提供命令很有用。
此功能也应适用于bash或者Bourne/Korn/POSIX shell。
Heredoc语法
语法为:
command <<EOF cmd1 cmd2 arg1 EOF
或者允许使用`EOF以自然的方式缩进shell脚本中的此处文档
command <<-EOF msg1 msg2 $var on line EOF
或者
command <<'EOF' cmd1 cmd2 arg1 $var won't expand as parameter substitution turned off by single quoting EOF
或者将其重定向并覆盖到名为my_output_file.txt的文件中:
command <<EOF > my_output_file.txt mesg1 msg2 msg3 $var on $foo EOF
或者将其重定向并追加到名为my_output_file.txt的文件中:
command <<EOF >> my_output_file.txt mesg1 msg2 msg3 $var on $foo EOF
例子
以下脚本将所需的内容写入名为/tmp/output.txt的文件:
#!/bin/bash OUT=/tmp/output.txt echo "Starting my script..." echo "Doing something..." cat <<EOF >$OUT Status of backup as on $(date) Backing up files $HOME and /etc/ EOF echo "Starting backup using rsync..."
您可以使用cat命令查看/tmp/output.txt:
$ cat /tmp/output.txt
输出示例:
Status of backup as on Thu Nov 16 17:00:21 IST 2016 Backing up files /home/Hyman and /etc/
禁用路径名/参数/变量扩展,命令替换,算术扩展
脚本中解释了$HOME之类的变量和$(date)之类的命令。
要禁用它,请对EOF使用单引号,如下所示:
#!/bin/bash OUT=/tmp/output.txt echo "Starting my script..." echo "Doing something..." # No parameter and variable expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. # If any part of word is quoted, the delimiter is the result of quote removal on word, and the lines in the here-document # are not expanded. So EOF is quoted as follows cat <<'EOF' >$OUT Status of backup as on $(date) Backing up files $HOME and /etc/ EOF echo "Starting backup using rsync..."
您可以使用cat命令查看/tmp/output.txt:
$ cat /tmp/output.txt
输出示例:
Status of backup as on $(date) Backing up files $HOME and /etc/
关于使用tee命令的注意事项
语法为:
tee /tmp/filename <<EOF >/dev/null line 1 line 2 line 3 $(cmd) $var on $foo EOF
或者通过在单引号中引用EOF来禁用变量替换/命令替换:
tee /tmp/filename <<'EOF' >/dev/null line 1 line 2 line 3 $(cmd) $var on $foo EOF
这是我更新的脚本:
#!/bin/bash OUT=/tmp/output.txt echo "Starting my script..." echo "Doing something..." tee $OUT <<EOF >/dev/null Status of backup as on $(date) Backing up files $HOME and /etc/ EOF echo "Starting backup using rsync..."
关于在此处使用内存的说明文档
这是我更新的脚本:
#!/bin/bash OUT=/tmp/output.txt ## in memory here docs ## thanks https://twitter.com/freebsdfrau exec 9<<EOF Status of backup as on $(date) Backing up files $HOME and /etc/ EOF ## continue echo "Starting my script..." echo "Doing something..." ## do it cat <&9 >$OUT echo "Starting backup using rsync..."