The answer depends on what, exactly, it is that you need. If your problem is only the newline that here-strings add, then all you need is echo -n
:
$ foo=bar
$ echo -n "$foo" | od -t x1
0000000 62 61 72
If you need to preserve the trailing newline(s) that command-substitution strips, or you truly need full binary safety, however, then there are no "work-arounds", unfortunately. Command-substitution will always strip trailing newline no matter what, and as mentioned in the comments, shell variables are not binary safe as they cannot contain NUL
s. If you need any of those things, then I'm pretty sure your only option is using temporary files.
As for using temporary files, however, the problem you state of finding a writable directory should be a small one, as /tmp
is always guaranteed to be writable by all unless you're working on a really weird system, or your script is supposed to run during an incomplete or failed boot, perhaps. In that case, you'll just have to switch to C instead. Otherwise, just use the mktemp
command. As for cleanup, you may want to use the trap
built-in command.