Search code examples
bashcatquotingbackticks

Bash complains about syntax errors in here-document when using backticks


I'm running the following piece of bash code:

cat << END_TEXT
       _             _ 
      | |           | |
  __ _| |__   ___ __| |
 / _` | '_ \ / __/ _` |
| (_| | |_) | (_| (_| |
 \__,_|_.__/ \___\__,_|
END_TEXT

and am getting an error:

bash: command substitution: line 1: syntax error near unexpected token `|'
bash: command substitution: line 1: ` | '_ \ / __/ _'

Solution

  • No need to escape backticks. Just use quoted here-doc string as:

    cat <<-'END_TEXT'
            _             _
           | |           | |
       __ _| |__   ___ __| |
      / _` | '_ \ / __/ _` |
     | (_| | |_) | (_| (_| |
      \__,_|_.__/ \___\__,_|
    END_TEXT
    

    As per man bash:

    If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion, the character sequence \<newline> is ignored, and \ must be used to quote the characters \, $, and `.