0

I'm trying to send data in a curl including new lines (from a git log) and bash just expands the new lines. I want them to literally be in the string when I use the environment var:

STR="Hello\nWorld"
echo $STR

Is currently giving me:

Hello
World

I want it to give me:

Hello\nWorld

My actual use-case:

function notify() {
  export RELEASE_NOTES=`git log $(git describe --tags --abbrev=0)..HEAD --no-merges --oneline --pretty=tformat:"%s [%cn]"`

  if [[ $SLACK_WEBHOOK_URL ]]; then
    curl -X POST -H 'Content-type: application/json' --data '{
      "blocks": [
        {
          "type": "section",
          "text": {
            "type": "mrkdwn",
            "text": "*Notes*:\n ```'$RELEASE_NOTES'```"
          }
        }
      ]
    }' $SLACK_WEBHOOK_URL
  fi
}
torek
  • 448,244
  • 59
  • 642
  • 775
creamcheese
  • 2,524
  • 3
  • 29
  • 55
  • `echo -e 'Hello\\nWorld'`- I understand that doesn't help your actual use-case. I assume this is for the notes? Have you tried `\r\n` instead of just `\n`? If it's for text inside of $RELEASE_NOTES you might just need to escape it – Conor Reid Mar 31 '22 at 16:05
  • 5
    Use `str='Hello\nWorld'`. The single quotes guarantee that no changes will be made to the quoted string. `echo $var` doesn't work in general. `echo "$var"` is better , but still doesn't always work. Use `printf '%s\n' "$var"`. Use [Shellcheck](https://www.shellcheck.net/) to check your code for common problems. Also see [Why is printf better than echo?](https://unix.stackexchange.com/q/65803/264812) and [Correct Bash and shell script variable capitalization](https://stackoverflow.com/q/673055/4154375). – pjh Mar 31 '22 at 16:15
  • 2
    Some versions of `echo` will interpret escape sequences (e.g. translate `\n` to newline); use `printf '%s\n' "$STR"` (as @pjh suggests) to avoid confusion. However, it also looks like your quoting is off in the `curl` command -- variable references like `$RELEASE_NOTES` should be in double-quotes to keep the shell from mangling them. I'd recommend using something like `jq` to create the JSON string; see [this question](https://stackoverflow.com/questions/65211894), although if `$RELEASE_NOTES` is already JSON-encoded, use `--argjson` instead of `--arg`. – Gordon Davisson Mar 31 '22 at 17:10
  • As mentioned, use `jq` to create a JSON file and then use `--data @file` to avoid all the escaping and potential conflicts – Diego Torres Milano Apr 01 '22 at 02:00

0 Answers0