Frage

I am using bash and this works on Linux:

read -r -d '' VAR<<-EOF
  Hello\nWorld
EOF

echo $VAR > trail

i.e the contents of the file on Linux is

Hello\nWorld

When i run on Solaris trial file has

Hello
World

The newline(\n) is being replaced with a newline. How can i avoid it?

Is it a problem with heredoc or the echo command?

[UPDATE]

Based on the explanation provided here:

echo -E $VAR > trail

worked fine on Solaris.

War es hilfreich?

Lösung 2

To complement @that other guy's helpful answer:

Even when it is bash executing your script, there are several ways in which the observed behavior - echo by default interpreting escape sequences such as \n - can come about:

  • shopt -s xpg_echo could be in effect, which makes the echo builtin interpret \ escape sequences by default.
  • enable -n echo could be in effect, which disables the echo builtin and runs the external executable by default - and that executable's behavior is platform-dependent.

These options are normally NOT inherited when you run a script, but there are still ways in which they could take effect:

  • If your interactive initialization files (e.g., ~/.bashrc) contain commands such as the above and you source (.) your script from an interactive shell.
  • When not sourcing your script: If your environment contains a BASH_ENV variable that points to a script, that script is sourced before your script runs; thus, if that script contains commands such as the above, they will affect your script.

Andere Tipps

The problem is with echo. Behavior is defined in POSIX, where interpretting \n is part of XSI but not basic POSIX itself.

You can avoid this on all platforms using printf (which is good practice anyways):

printf "%s\n" "$VAR"

This is not a problem for bash by the way. If you had used #!/usr/bin/env bash as the shebang (and also not run the script with sh script), behavior would have been consistent.

If you use #!/bin/sh, you'll get whichever shell the system uses as a default, with varying behaviors like this.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top