oarfish
oarfish

Reputation: 4641

How can I limit readonly variable scope to a function?

I'm defining functions in a script with readonly local variables like this:

test.sh

function test_function() {
    readonly local foo="bar"
}

Before sourcing, foo is of course undefined

$> echo $foo

$>

But then when I source and run the function

$> source test.sh
$> test_function
$> echo $foo
bar
$>

suddenly the variable has leaked beyond its scope. Removing readonly solves the problem. What am I misunderstanding about the use of areadonly and local and can both be used without this problem?

The use case is that I get errors/warnings, when calling test_function multiple times, because the variable is supposed to be readonly, but already defined.

Upvotes: 3

Views: 597

Answers (1)

John1024
John1024

Reputation: 113984

Replace:

readonly local foo="bar"

with:

local -r foo="bar"

The issue is that readonly local foo="bar" defines two readonly variables: one named local and one namedfoo. It does not create any local variables.

By contrast, local -r foo="bar" creates a variable named foo which is both local and readonly.

As David C Rankin points out, once you have created a global read-only variable, you cannot unset it. You need to close your existing shell and start a new one.

Upvotes: 5

Related Questions