Home > Blockchain >  Is there a way to escape $ and single quotes together in bash?
Is there a way to escape $ and single quotes together in bash?

Time:11-17

I am running the following code, but if env.body contains $, it will be translated as a variable.

printf -v markdown_message_unescaped %b "<${{ env.URL }}|*${{ env.body }}*>\n"
jq -n -r --arg text "$markdown_message_unescaped" '{"text": $text}'|curl -X POST -H 'Authorization: Bearer ${{ secrets.TOKEN }}' -H "Content-Type: application/json" -d @-  ${{ env.URL }}
 

I modified the code to look like the following to escape $, but this does not work well if single quotes are included in env.body.

body='${{ env.body }}'
printf -v markdown_message_unescaped %b "<${{ env.URL }}|*$body*>\n"
jq -n -r --arg text "$markdown_message_unescaped" '{"text": $text}'|curl -X POST -H 'Authorization: Bearer ${{ secrets.TOKEN }}' -H "Content-Type: application/json" -d @-  ${{ env.URL }}

Is there any way to fix this?

CodePudding user response:

You can use a heredoc, which will preserve everything literally (except the chosen EOF string). You must use the yaml pipe operator to preserve new lines, as they are required for the heredoc syntax.

run: |
  markdown_msg=$(
  cat <<"EOF"
  ${{ env.body }}
  EOF
  )
  printf -v markdown_msg %b "$markdown_msg"
  jq --arg text "$markdown_msg" # etc

It's important that bash sees EOF on a single line, with no leading or trailing whitespace. Indentation in the yaml file will be stripped before it's passed to bash.

  • Related