[PATCH] command substitution with trailing newlines (was Re: [PATCH] Add
From:
Kevin Pulo
Subject:
[PATCH] command substitution with trailing newlines (was Re: [PATCH] Add shopts for ...)
Date:
Fri, 29 Aug 2025 21:15:55 +1000
On Fri, 29 Aug 2025 at 01:00, Koichi Murase <myoga.murase@gmail.com> wrote:
> If the feature is really desired by the community as an essential feature, it
> should be implemented as a new syntax.
I looked at adding alternate syntax for doing command substitution without
stripping trailing newlines, and it turned out to be easier than I expected.
This patch adds the syntax ${;cmd;}, which is handled identically to ${ cmd;}
except that trailing newlines are preserved.
It's only necessary to do a nofork version, because if someone deliberately
wants to run inside a subshell (ie. fork instead of no-fork) then they can just
do that explicitly with ${;(cmd;);}.
I don't care much about the choice of character, ie. if something else would be
better than ';'. A single character is definitely easier to parse and handle
than some of the fancier previous proposals, such as
https://lists.gnu.org/archive/html/bug-bash/2021-01/msg00269.html which is very
extensible, but would be a lot more work.
It seems to work fine, but I might've missed something. If there's interest in
adopting this, then I'd be happy to update the tests and docs. Otherwise, I'm
curious to hear if there might be any potential problems with adding this, or
what else it would require to be accepted.
bash-5.3$ echo "[$(echo foobar)]"
[foobar]
bash-5.3$ echo "[${ echo foobar;}]"
[foobar]
bash-5.3$ echo "[${;echo foobar;}]"
[foobar
]
bash-5.3$ echo "[${;echo -e 'foobar\n';}]"
[foobar
]
bash-5.3$ echo "[${;echo "(${;echo foobar;})";}]"
[(foobar
)
]
bash-5.3$
With this, my original illustrative example script becomes:
my_result=${;some | complex | pipeline;}
while :; do
if is_any_good "$my_result"; then
break
else
my_result=${;echo -n "$my_result" | some | further | processing;}
fi
done
echo -n "$my_result" | final_processing
which I think is about as good as possible. It still can't use here-strings,
but using echo -n is maybe better anyway, since it more clearly shows the
left-to-right data flow.
Kev