Shell – Avoid backslash expansion with echo in dash

dashechoshellshell-script

First create a file with this exact content:

a\nb

I named this file foo, if I run the following, it prints the exact content of the file:

bash -c 'bar=$(cat foo);echo "$bar"'

But if you run it with sh instead of bash the result is:

a
b

The problem here is that the \n is being translated to a new line character that I do not want to.

My machine default sh is dash, the target machine is running an embedded linux with ash builtin busybox, so it is very minimalist, it works very similar to dash not bash.

If I run just sh -c 'cat foo' it get the expected result, but I want it inside the variable, how could I do it?

Best Answer

Actually the shell forks and executes the command. But each time a command (which is not a built-in) is executed, the shell forks. That's how shells work, and that's unavoidable.

Note: the shell doesn't translate anything. The echo command may. But you can use printf instead:

your_shell -c 'bar=$(cat foo); printf %s "$bar"'
Related Question