First create a file with this exact content:


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:


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?


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"'
  • I believe there are a misunderstanding here, my problem is not with the variable, the sh -c is just for simplify, the problem is that dash is translating the \n which I do not want to. – Tiago Pimenta Jan 4 '15 at 23:50
  • 1
    @TiagoPimenta I've updated my answer: it's echo that may do some translation. If you're not sure of the context (e.g. whether the string can contain special sequences), avoid echo. – vinc17 Jan 4 '15 at 23:55
  • well, it worked, but it is really strange for me, dash acts as echo -e ever! – Tiago Pimenta Jan 4 '15 at 23:58
  • 1
    @TiagoPimenta The problem is not dash, but bash, whose echo does not conform to POSIX echo, which does not allow any option (-n is a special argument). – vinc17 Jan 5 '15 at 0:02
  • That's how most shells work, which is, as I believe, a conseqeunce of their having to open a pipe for $( the subshell's output ). ksh93 definitely does not fork in that case - which is, as I believe, a consequence of its using Korn's io lib rather than stdio. – mikeserv Jan 5 '15 at 0:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.