28

I have a text like this:

foo bar
`which which`

If I do this using heredoc, I get a blank file:

➜  ~  echo <<EOT > out
heredoc> foo bar
heredoc> `which which`
heredoc> EOT
➜  ~  cat out

➜  ~  

How can I do this?

Edit

Oh sorry, I meant to do cat. Problem is that it writes this to the file: which: shell built-in command, ie, evaluations backticks. Any way to do this without evaluating?

With cat, I get

➜  ~  cat <<EOT > out
heredoc> foo bar
heredoc> `which which`
heredoc> EOT
➜  ~  cat out
foo bar
which: shell built-in command
➜  ~  

I don't want which which to be evaluated.

doubleDown
  • 8,048
  • 1
  • 32
  • 48
user1527166
  • 3,229
  • 5
  • 26
  • 26

1 Answers1

59

Quote the label to prevent the backticks from being evaluated.

$ cat << "EOT" > out
foo bar
`which which`
EOT

$ cat out
foo bar
`which which`
dogbane
  • 266,786
  • 75
  • 396
  • 414
  • Oh sorry, I meant to do cat. Problem is that it writes this to the file: `which: shell built-in command`, ie, evaluations backticks. Any way to do this without evaluating? – user1527166 Oct 29 '12 at 13:04
  • Quote the label to prevent the backticks from being evaluated. – dogbane Oct 29 '12 at 13:06
  • 12
    FYI this will also disable other bash expression (such as variable evaluation) from occurring. To just disable backtick evaluation you can escape the backticks by adding a backslash, e.g. '\\`' – Keith Hughitt Feb 06 '15 at 20:43
  • 24
    Why does this work?? There is no sanity in Bash. – tsbertalan Jul 27 '16 at 12:54
  • 5
    Here's the relevant documentation on turning off substitution in here doc : http://tldp.org/LDP/abs/html/here-docs.html#EX71C, so there's 3 options : either `\EOT`, `'EOT'` or `"EOT"`. – bric3 Jun 03 '19 at 15:45
  • @tsbertalan There's plenty of sanity to this! In heredocs, expressions are evaluated, such as variables being expanded to their value. Backticks are used in shell scripts to represent an expression statement, similar to `$(...)`. To turn off evaulation, you have to use a delimiter that is marked to turn off evaluation, and consistently, `\` is the escape character used to prevent evaluations throughout shell, including heredocs. – Nick Bull Mar 27 '21 at 16:04