In bash, when an output is captured into variable using $(...)
, an annoying newline is appended. However, I have an output that sometimes ends in a newline, and sometimes not. I want the output to be captured as-is.
In my real problem, the strings may contain several lines, but the last may or may not close with a newline, and this property should be preserved.
In the style of this answer at Stack Exchange, my minimal working example looks like this:
#!/bin/bash
newlinetest() {
if [ "$1" = 'with' ]; then
printf '%s\n' 'Text with newline'
else
printf '%s' 'Text without newline'
fi
}
s="$(newlinetest with ; printf '%s' 'x')"
s="${s%?}"
printf '%s%s%s\n' '(' "${s}" ')'
s="$(newlinetest without ; printf '%s' 'x')"
s="${s%?}"
printf '%s%s%s\n' '(' "${s}" ')'
It does what it should do, but IMHO this looks like an ugly hack. Is there any other elegant way to solve this? Maybe something that involves mapfile
or read
? A solution without external tools would be very welcome.
printf
instead ofecho
, which makes it more wordy. I'm unsure what's a "hack" about it though.echo x
appends the letter x followed by a newline. The newline gets trimmed by$()
, and afterwards the x is removed. IMHO, the obvious newline makes the variant withecho
even more obfuscated.