help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: any plans for command substitution that preserves trailing newlines?


From: Greg Wooledge
Subject: Re: any plans for command substitution that preserves trailing newlines?
Date: Wed, 2 Jun 2021 11:15:53 -0400

On Wed, Jun 02, 2021 at 11:04:32AM -0400, Chet Ramey wrote:
> On 6/1/21 5:03 PM, Christoph Anton Mitterer wrote:
> 
> > So basically:
> > -------------------------------------
> > LC_ALL=<whatever>
> > 
> > subst="$( command; rc=$?; printf 'x'; exit $rc )"
> > 
> > #remember rc if necessary
> > rc=$?
> > 
> > #remove the sentinel
> > LC_ALL=C subst="${subst%x}"
> > -------------------------------------
> > is guaranteed to work for every locale and every sentinel value (not
> > just 'x')... and should also be portable, right?
> 
> That's the basic idea, yes.
> 
> I would save the locale's variable values, use LC_CTYPE instead of LC_ALL,
> put the assignment to LC_CTYPE as its own command (though that's not
> strictly necessary), and make sure to restore the locale afterward.
> 
> Since you can't be sure what locale variables, if any, exist in the current
> shell's execution environment, it's simpler to save and restore them all.
> If you want, you can just check whether or not LC_CTYPE (or LC_ALL,
> depending on your preference) is set and save the original value.
> You already know which variables you've set in the script.

Are we talking about bash or sh here?  If it's bash, you can use a
function with LC_ALL or LC_CTYPE scoped as a local variable.

If it's sh, then you get horror shows like

LC_CTYPE=C eval 'assignment command with extra backslashes here'

because there's no way to force single-command scoping without an actual
command (and as the OP observed, assignments don't count).  And you can't
use a subshell, because then the assignment wouldn't "work".



reply via email to

[Prev in Thread] Current Thread [Next in Thread]