代码之家  ›  专栏  ›  技术社区  ›  Salami

使用cat将字符串写入文件时防止变量替换

  •  1
  • Salami  · 技术社区  · 7 年前

    我想在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) 正在执行,并且输出正在写入文件。如何在不展开任何内容的情况下编写提供的文本字符串?

    1 回复  |  直到 6 年前
        1
  •  5
  •   PesaThe    7 年前
    cat >./foo.bar <<'EOL'
    t=$(ping 8.8.8.8)
    EOL
    

    Bash Reference Manual :

    [n]<<[-]word

    如果任何部分 word 是引号,分隔符是引号的结果 删除时间 单词 ,并且此处文档中的行不会展开。