Binary safe bash 'here string'?

358 views Asked by At

I'd like to save output of a command to a variable for later multiple uses. Bash provides Here String functionality for that purpose. However it is not binary safe. It sometimes adds new lines:

$ a=''
$ xxd <<< "$a"
00000000: 0a     

Is there any binary safe alternative?

I use the variable in for loop so IIUIC it disqualifies tee command and any pipe like solution. I'd also prefer something else than temporary files as the are slow and clumsy to work with (require a writable directory, clean-up).

1

There are 1 answers

0
Dolda2000 On

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 NULs. 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.