sh: Attempt to change readonly var doesn't stop script

Code:
test=56
readonly test


test_internal ()
{
    local test=12

    #test=12    # This would stop script execution

    echo "Internal: '$test'"
}



test_internal
echo "$test"


exit
 
Looks like you have two variables named "test'. One is global to the script and the other is local to the function. This makes them different variables, no?
 
There are 2 variables, but the readonly flag is preserved. From the sh(1) page:

When a variable is made local, it inherits the initial value and exported and readonly flags from the variable with the same name in the surrounding scope, if there is one.

So, it continues to be readonly in this case.
 
That's a bit counter-intuitive to me. The local test variable should be a completely new variable if looked from the point of other programming languages. What's the reason for this?
 
I would agree that it is less than useful. I was thinking the Single Unix Specification might shed some light on it, but it doesn't address the local shell builtin. It does have the readonly builtin:
The values of variables with the readonly attribute cannot be changed by subsequent assignment, nor can those variables be unset by the unset utility.

From that point of view, it's pretty clear, once readonly, always readonly, no matter the scoping.
 
Back
Top