How to create a read-only local variable in bash?

How to create local and declare -r variable (read-only) in bash?

If I do this:

 function x { declare -r var=val } 

Then I just get a global var that is read-only

If I do this:

 function x { local var=val } 

If I do this:

 function x { local var=val declare -r var } 

Then I get global again (I can access var from other functions).

How to combine both local and read-only in bash?

+6
source share
2 answers

Even if help local does not mention this in Bash 3.x, local can accept the same parameters as declare (at least Bash 4.3.30, this documentation supervision has been fixed).

So you can just do:

 local -r var=val 

However, declare inside the function behaves like local by default, as the comments indicate ruakh, so your first attempt should also have been to create a read-only local variable.

In Bash 4.2 and later, you can override this with the declare -g option to create a global variable even from within the function (Bash 3.x does not support this.)

+15
source

If you want to use exit code, you can use this approach

 function f { local t=$(ls asdf 2>&1) c=$?; local -rt=$t; echo 'Exit code: '$c; echo 'Value: '$t; } f 

Print

 Exit code: 1 Value: ls: asdf: No such file or directory 
0
source

All Articles