Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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: ` | '_ \ / __/ _'
like image 288
einpoklum Avatar asked Feb 12 '18 11:02

einpoklum


2 Answers

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 `.

like image 196
anubhava Avatar answered Nov 17 '22 00:11

anubhava


It's the backticks. Most content in a here-document is not intrepreted and used as-is, but backticks change this.

The solution: Escape them, even though it messes up the layout of your script:

cat << END_TEXT
       _             _ 
      | |           | |
  __ _| |__   ___ __| |
 / _\` | '_ \ / __/ _\` |
| (_| | |_) | (_| (_| |
 \__,_|_.__/ \___\__,_|
END_TEXT
like image 1
einpoklum Avatar answered Nov 17 '22 01:11

einpoklum