3

I'd like to write a string to a file in a bash script, but don't know how prevent variables from being expanded. An example script:

#!/bin/bash

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

Produces the output:

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

So it seems $(ping 8.8.8.8) is being executed and the output is being written to the file. How do I write the literal string provided without expanding anything?

codeforester
  • 39,467
  • 16
  • 112
  • 140
Salami
  • 1,048
  • 1
  • 10
  • 17
  • I think the reason I didn't find the linked question was because I didn't know what I was doing was called a 'here-document'. – Salami Jan 21 '18 at 00:50

1 Answers1

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

Quoting Bash Reference Manual:

[n]<<[-]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.

PesaThe
  • 7,259
  • 1
  • 19
  • 43