Thanks for the workaround. It's odd that it appears to work for scalar types in
both cases, but not indexed arrays (in the second case) or associative arrays
(in both cases). Would be nice to save an extra line when initializing and
freezing each variable like you can do with declare/local.
Also, apologies for the original formatting. It was my first post. Here it is
re-formatted in plain text for posterity:
# ====================
declare string
declare -i int
declare -a array
init_vars () {
readonly string="foo"
readonly int=100
readonly array=(1 2)
# Print the (hopefully) readonly variables
declare -p string int array
}
init_vars
# ====================
This prints the expected output (IMO):
# ====================
declare -r string="foo"
declare -ir int="100"
declare -ar array=([0]="1" [1]="2")
# ====================
Now if I attempt to do the same for local variables declared as such:
# ====================
foo () {
local string
local -i int
local -a array
init_vars
}
foo
# ====================
This prints different output for the indexed array only:
# ====================
declare -r string="foo"
declare -ir int="100"
declare -ar array
# ====================
-Will
On Monday, June 3, 2024 at 03:57:23 PM PDT, Zachary Santer <[email protected]>
wrote:
On Mon, Jun 3, 2024 at 6:16 PM Will Allan via Bug reports for the GNU
Bourne Again SHell <[email protected]> wrote:
>
> init_vars () { readonly string="foo" readonly int=100 readonly array=(1 2)
My understanding is that the readonly builtin isn't supposed to handle
compound assignment syntax like the declare and local builtins
do.[1][2] That it might try to anyway is likely unintended.
Your best bet is to do:
array=(1 2)
readonly array
instead of trying to combine the two. This should give you the
behavior you expect.
[1]:
https://www.gnu.org/software/bash/manual/html_node/Bourne-Shell-Builtins.html#index-readonly
[2]:
https://www.gnu.org/software/bash/manual/html_node/Arrays.html