【问题标题】:Prevent variable substitution when writing string to file with cat <<EOL [duplicate]使用 cat <<EOL [重复] 将字符串写入文件时防止变量替换
【发布时间】:2018-06-29 22:02:46
【问题描述】:

我想在 bash 脚本中将字符串写入文件,但不知道如何防止变量被扩展。示例脚本:

#!/bin/bash

cat >./foo.bar <<EOL
t=$(ping 8.8.8.8)
EOL

产生输出:

t=
Pinging 8.8.8.8 with 32 bytes of data:
Reply from 8.8.8.8: bytes=32 time=17ms TTL=57
Reply from 8.8.8.8: bytes=32 time=16ms TTL=57
Reply from 8.8.8.8: bytes=32 time=17ms TTL=57
Reply from 8.8.8.8: bytes=32 time=17ms TTL=57

Ping statistics for 8.8.8.8:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 16ms, Maximum = 17ms, Average = 16ms

看来$(ping 8.8.8.8) 正在执行,并且输出正在写入文件。如何在不扩展任何内容的情况下编写提供的文字字符串?

【问题讨论】:

  • 我认为我没有找到链接问题的原因是因为我不知道我在做什么被称为“此处文档”。

标签: bash shell heredoc


【解决方案1】:
cat >./foo.bar <<'EOL'
t=$(ping 8.8.8.8)
EOL

引用Bash Reference Manual:

[n]&lt;&lt;[-]word

如果word的任何部分被引用,分隔符就是引用的结果 在word 上删除,并且此处文档中的行没有展开。

【讨论】:

    猜你喜欢
    • 2015-04-18
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    • 2013-02-08
    • 2019-10-09
    • 1970-01-01
    • 2020-12-04
    • 1970-01-01
    相关资源
    最近更新 更多