Discussion:
[Help-bash] Simplest way to keep trailing newlines when reading a file into a bash variable
Greg Wooledge
2018-05-21 13:27:09 UTC
Permalink
It is simple to read a file with training newlines removed into a bash variable.
x=$(< file)
Supposedly, it should be reasonable to expect a solution with as
little code as possible (e.g., no intermediate variable, one line).
But I haven't found such a solution. Does anybody know such a simplest
solution? Thanks.
Solution 1:

x=$(cat file; printf z) x=${x%z}

Number of intermediate variables: 0

Number of lines of code: 1

Number of bytes dropped on the floor: 1 (0x00, NUL)


Solution 2:

IFS= read -rd '' x < <(tr -d \\0 < file)

Number of intermediate variables: 0

Number of lines of code: 1

Number of bytes dropped on the floor: 1 (0x00, NUL)


Solution 3:

Stop writing in bash. Use a real programming language instead.

Number of intermediate variables: depends on the language

Number of lines of code: depends on the language

Number of bytes dropped on the floor: depends on the language

For example, in Tcl:

set x [read $my_file_descriptor]

will read the entire contents of the already-open file descriptor and
store it in the variable x. This includes NUL bytes. This includes
trailing newlines. This includes everything Tcl can handle, which is
the Unicode Basic Multilingual Plane plus the NUL byte (which is encoded
specially). If you need Unicode outside of the BMP, well, you're out of
luck. Stop writing in Tcl (for now).

Maybe Perl can do it? Maybe Python? Ruby? I don't know.
Supposedly, it should be reasonable to expect a solution with as
little code as possible
Why on EARTH would you hold such an expectation? You've been doing
bash programming for a while now. Surely you've developed some idea
of how fragile and hackish it is.

Loading...