Declaring a local variable in a bash function makes that variable only visible inside the function itself and its children, so if I run:
#!/bin/bash
set -e
func_one() {
echo "${var}"
}
func_two() {
local -r var="var from func_two"
func_one
}
func_two
The output is:
var from func_two
Even if the var variable is declared as local and readonly inside func_two can be accessed from the function func_one. It is possible, in the latter, to declare a variable with the same name also local and readonly:
#!/bin/bash
set -e
func_one() {
local -r var="var from func_one"
echo "${var}"
}
func_two() {
local -r var="var from func_two"
func_one
}
func_two
The output is:
var from func_one
The same happens if func_one is called from an EXIT trap:
#!/bin/bash
set -e
func_one() {
local -r var="var from func_one"
echo "${var}"
}
func_two() {
local -r var="var from func_two"
trap 'func_one' EXIT
echo "${var}"
}
func_two
Running the code I receive:
var from func_two
var from func_one
However, if the EXIT trap is executed after an error (set -e option makes the script exit immediately if a command exits with a non zero status). It looks like it's not possible to reassign the var variable inside func_one:
#!/bin/bash
set -e
func_one() {
local -r var="var from func_one"
echo "${var}"
}
func_two() {
local -r var="var from func_two"
trap 'func_one' EXIT
echo "${var}"
false
}
func_two
Running the code I receive:
var from func_two
local: var: readonly variable
Can anyone clarify to me why this happens? Thank you in advance.