Search code examples
linuxbashshelldash-shell

echo prints "\n" differently between /bin/sh and /bin/bash


I have a shell script that reads a multi-line JSON string from cURL:

r=$(curl -H "X-Vault-Token: $VAULT_TOKEN" -fs $VAULT_ADDR/v1/$1)

If I run echo $r and execute the script with /bin/sh I see that newline characters inside the JSON are interpreted as newlines:

{"data": {"value": "foo
bar"}}

but when I execute the script with /bin/bash the newlines are literal:

{"data": {"value": "foo\nbar"}}

I'd like the newline to be literal when using either /bin/sh and /bin/bash. How do I stop /bin/sh from interpreting the newlines?

file -h /bin/sh
/bin/sh: symbolic link to dash

Solution

  • Use printf instead of echo.

    printf '%s\n' "$r"
    

    From the POSIX spec for echo:

    It is not possible to use echo portably across all POSIX systems unless both -n (as the first argument) and escape sequences are omitted.

    Reading the APPLICATION USAGE section in full is strongly recommended.