加入收藏 | 设为首页 | 会员中心 | 我要投稿 淮安站长网 (https://www.0517zz.cn/)- 运营、云管理、经验、智能边缘、云硬盘!
当前位置: 首页 > 建站 > 正文

Bash脚本中如何使用here文档将数据写入文件

发布时间:2018-11-14 14:45:46 所属栏目:建站 来源:佚名
导读:副标题#e# here document (LCTT 译注:here 文档又称作 heredoc )不是什么特殊的东西,,只是一种 I/O 重定向方式,它告诉 bash shell 从当前源读取输入,直到读取到只有分隔符的行。 这对于向 ftp、cat、echo、ssh 和许多其他有用的 Linux/Unix 命令提供

示例输出:

  1. Status of backup as on $(date)
  2. Backing up files $HOME and /etc/

关于 tee 命令的使用

语法是:

  1. tee /tmp/filename <<EOF >/dev/null
  2. line 1
  3. line 2
  4. line 3
  5. $(cmd)
  6. $var on $foo
  7. EOF

或者通过在单引号中引用 EOF 来禁用变量替换和命令替换:

  1. tee /tmp/filename <<'EOF' >/dev/null
  2. line 1
  3. line 2
  4. line 3
  5. $(cmd)
  6. $var on $foo
  7. EOF

这是我更新的脚本:

  1. #!/bin/bash
  2. OUT=/tmp/output.txt
  3.  
  4. echo "Starting my script..."
  5. echo "Doing something..."
  6.  
  7. tee $OUT <<EOF >/dev/null
  8. Status of backup as on $(date)
  9. Backing up files $HOME and /etc/
  10. EOF
  11.  
  12. echo "Starting backup using rsync..."

关于内存 here 文档的使用

这是我更新的脚本:

  1. #!/bin/bash
  2. OUT=/tmp/output.txt
  3.  
  4. ## in memory here docs
  5. ## thanks https://twitter.com/freebsdfrau
  6. exec 9<<EOF
  7. Status of backup as on $(date)
  8. Backing up files $HOME and /etc/
  9. EOF
  10.  
  11. ## continue
  12. echo "Starting my script..."
  13. echo "Doing something..."
  14.  
  15. ## do it
  16. cat <&9 >$OUT
  17.  
  18. echo "Starting backup using rsync..."

(编辑:淮安站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

推荐文章
    热点阅读