0

Original string getting mutated while printing with echo statement.

#!/bin/bash

response='{\\\"test\\\":\\\"data\\\"}'
echo $response;

Actual Output - {\\"test\\":\\"data\\"}

Expected output - {\\\"test\\\":\\\"data\\\"}

  • 1
    I see the output is correct: http://ideone.com/wWO8vc. – Yang Jul 04 '19 at 18:28
  • 1
    How are you running the script? Your actual output is what I would expect from a POSIX-compliant implementation of `echo`, which `bash` does not (by default) provide. – chepner Jul 04 '19 at 18:33
  • For anyone saying it "works for me": different versions of `echo` have different behavior. Some interpret escapes, some don't, some only interpret them if given the `-e` option, and some will print the "-e" as part of their output. It's all hopelessly inconsistent. According to the [POSIX spec](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html), "It is not possible to use `echo` portably across all POSIX systems unless both `-n` (as the first argument) and escape sequences are omitted." So use `printf` instead. – Gordon Davisson Jul 04 '19 at 19:46

2 Answers2

2
  1. quote your variables (see https://mywiki.wooledge.org/Quotes)
  2. use printf, not echo (see https://unix.stackexchange.com/q/65803/133219)

e.g.:

$ response='{\\\"test\\\":\\\"data\\\"}'
$ printf '%s\n' "$response"
{\\\"test\\\":\\\"data\\\"}
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
0

This works as expected in bash, but you are instead running it with sh. See: Why does my bash code fail when I run it with sh?

However, when you want to print a string exactly as is, use printf:

response='{\\\"test\\\":\\\"data\\\"}'
printf '%s\n' "$response"

This works correctly for all values in all shells, including response='*' reponse='-n' and response='foo bar'

that other guy
  • 116,971
  • 11
  • 170
  • 194