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: Chet Ramey
Subject: Re: any plans for command substitution that preserves trailing newlines?
Date: Wed, 2 Jun 2021 11:04:32 -0400
User-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:78.0) Gecko/20100101 Thunderbird/78.10.2

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.



And:
For UTF-8, the same work even when not setting LC_ALL=C at the removal,
right?


What I coudln't find out was:
Does:
   LC_ALL=C subst="${subst%x}"
work as I'd expect, that is LC_ALL being active *ony* for the
assignment and parameter expansion?

That's not a reasonable expectation. Multiple assignment statements without
a command all affect the current shell environment.


        If no command name results, variable assignments shall affect the
    current execution environment.

Which is what this says.

But when I tried it out, the environment wasn't affected, i.e.

If you want to change what `locale' -- which is an external command --
sees in its environment, you have to export the appropriate variable. If
you don't have any of the LC_ variables or LANG in your environment, which
is not unusual, `locale' is going to show you the system default locale,
whatever it is. That may or may not be the same as the current shell locale
depending on what changes you've made to shell variables.

--
``The lyf so short, the craft so long to lerne.'' - Chaucer
                 ``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, UTech, CWRU    chet@case.edu    http://tiswww.cwru.edu/~chet/



reply via email to

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