7

The following script fails when run with bash 4.4.20(1)

#!/bin/bash
bar() {
  local args=("y")
}

foo() {
  local -r args=("x")
  bar
}

foo

with error line 3: args: readonly variable but succeeds when run with bash 4.2.46(2), which makes sense after reading 24.2. Local Variables.

The following script with non-array variables runs without any issues:

#!/bin/bash
bar() {
  local args="y"
}

foo() {
  local -r args="x"
  bar
}

foo

I could not find any changes that explain the difference between bash 4.2.46(2) and bash 4.4.20(1).

Q: is this a bug in bash 4.4.20(1)? if this is expected behavior then why does the second script not fail?

1 Answer 1

6

Your script runs correctly with release 5.1 of the bash shell, but not with intermediate releases after 4.3.

The bug or bugs might have been introduced around release 4.3 or 4.4. Multiple changes touched on how read-only declarations and variables work in the development leading up to both releases.

There are at least two entries in the change log that may relate to fixing the involved bugs:

  1. For bash-5.0-alpha, the change log has this to say (I'm assuming that referencing the readonly builtin also means local -r was affected):

Fixed a bug that could cause builtins like readonly to behave differently when applied to arrays and scalar variables within functions.

  1. For bash-5.1-alpha, an additional bug that could be related to this is also mentioned:

Fixed a bug that caused local variables with the same name as variables appearing in a function's temporary environment to not be marked as local.


Bisecting using the shell's Git repository and your script, we arrive at the bug being introduced with bash-4.4-rc1, and then later fixed in bash-5.1-alpha. Since both are big commits, it's difficult to point to any particular changes in the code.

2
  • The bug (if it's really a bug, but I think it is) is present in bash 5.0.17 on Ubuntu 20.04. Commented Feb 22, 2023 at 11:25
  • @Kusalananda thank you very much for your extensive reply, I agree with your analysis. As a workaround I will remove all '-r' references from our codebase.
    – Dennis
    Commented Feb 23, 2023 at 7:02

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.