7

I am trying to escape backtick in bash for long time. I tried escaping with \ but it does not work.

Is it possible to escape backtick in bash?

Sample code

I="hello.pdf"

var1=`cat <<EOL
![](../images/${I%.*}.png)
\`\`\`sql
some code here

\`\`\`

EOL`

echo "$var1"

Required output

![](../images/hello.png)
```sql
some code here

```
Cyrus
  • 84,225
  • 14
  • 89
  • 153
BhishanPoudel
  • 15,974
  • 21
  • 108
  • 169
  • 5
    Just use `$(...)` instead of backticks? – Robert Apr 07 '20 at 19:27
  • 2
    Really, that. `$(...)` has been the preferred/modern syntax ever since the 1992 publication of POSIX.2; that's nearing on 30 years ago! There's no excuse for using backticks for command substitution in modern code. – Charles Duffy Apr 07 '20 at 19:32
  • Relevant: [BashFAQ #82](http://mywiki.wooledge.org/BashFAQ/082), [What is the difference between $(command) and \`command\` in shell programming?](https://stackoverflow.com/questions/4708549/what-is-the-difference-between-command-and-command-in-shell-programming) – Charles Duffy Apr 07 '20 at 19:41

1 Answers1

5

Use $(...) instead of backtick syntax for the outer command substitution. Thus:

I='foo.png'
var1=$(cat <<EOL
![](../images/${I%.*}.png)
\`\`\`sql
some code here

\`\`\`
EOL
)
echo "$var1"

See this running, and emitting your desired output, at https://ideone.com/nbOrIu


Otherwise, you need more backslashes:

I='foo.png'
var1=`cat <<EOL
![](../images/${I%.*}.png)
\\\`\\\`\\\`sql
some code here

\\\`\\\`\\\`
EOL
`
echo "$var1"

...and if you were to nest backticks inside backticks, you'd need to multiply your backslashes yet again. Just Say No to backtick-based command substitution.


By the way, something you might consider to evade this problem altogether:

I='foo.png'
fence='```'
var1=$(cat <<EOL
![](../images/${I%.*}.png)
${fence}sql
some code here

${fence}
EOL
)
echo "$var1"

...putting the literal backticks in a variable means you no longer need any kind of escaping to prevent them from being treated as syntax.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441