Search code examples
bashcommand-substitution

How to escape backticks in bash


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

```

Solution

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