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

问题描述 投票:0回答:1

这个问题在这里已有答案:

我想在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个回答
3
投票
cat >./foo.bar <<'EOL'
t=$(ping 8.8.8.8)
EOL

引用Bash Reference Manual

[n]<<[-]word

如果引用word的任何部分,则分隔符是word上的引用删除的结果,并且here-document中的行不会被展开。

© www.soinside.com 2019 - 2024. All rights reserved.