help-bash
[Top][All Lists]
Advanced

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

Re: command substitution subshell exits when assigning to readonly varia


From: Chet Ramey
Subject: Re: command substitution subshell exits when assigning to readonly variable
Date: Wed, 18 Oct 2023 10:30:52 -0400
User-agent: Mozilla Thunderbird

On 10/17/23 6:38 PM, Philippe Cerfon wrote:
Dear list.

When I have a script like:
echo 1
V="$(
echo a >&2
false
echo b >&2
)"
echo 2

I get:
1
a
b
2
when executing or sourcing it.


But when I have:
readonly R=.

echo 1
V="$(
echo a >&2
R=
echo b >&2
)"
echo 2

I get:
1
a
b.sh: line 9: R: readonly variable
2
when executing it, and something similar when sourcing it.


set -e is not used. And something like R= || true doesn't help either.


This does not seem to happen, when outside a command substitution:
readonly R=.

echo 1
R=
echo 2

gives:
1
bash: R: readonly variable
2
regardless of whether executed or sourced.

Assigning to a readonly variable is a variable assignment error, which
causes a non-interactive shell to exit in posix mode and to jump back
to the top level, abandoning execution of the current command, in default
mode.

Command substitution inherits whether or not it's an interactive shell
from its caller. If you're executing it from the command line, the
shell is interactive. If you're running a script, it's not.

The `current command' in a command substitution is the list between the
parentheses -- a compound command. Since that is the only command in the
command substitution, jumping back to the top level results in the
command substitution finding no more commands to execute and exiting.

So either way, the variable assignment error results in the command
substitution not executing any more commands.


Also:
R= 2> /dev/null
doesn't do what one might hope it would. I assume this is because the
redirection happens after the assignment?
So the only thing one could do is exec 2> /dev/null before?

Yes, that would work.

--
``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]