Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How do I create both local and declare -r (read-only) variable in bash?

If I do:

function x {
    declare -r var=val
}

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

If I do:

function x {
    local var=val
}

If I do:

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

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

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

like image 900
bodacydo Avatar asked Dec 01 '15 02:12

bodacydo


People also ask

How do I create a read only variable in bash?

To add more nuance, readonly may be used to change a locally declared variable property to readonly, not affecting scope. Note: adding -g flag to the declare statement (e.g. declare -rg a="a1" ) makes the variable scope global. (thanks @chepner). Note: readonly is a "Special Builtin".

How do I make a variable read only in Linux?

Shell provides a way to mark variables as read-only by using the read-only command. After a variable is marked read-only, its value cannot be changed. /bin/sh: NAME: This variable is read only.

How do you set local variables in bash?

The easiest way to set environment variables in Bash is to use the “export” keyword followed by the variable name, an equal sign and the value to be assigned to the environment variable.

What is the meaning of ${ 1 in bash?

This answer is useful. This answer is not useful. Show activity on this post. ${1#*-} deletes the shortest match of *- , a glob-like pattern from $1 variable. E.g. abcdef-xyz-foo -> xyz-foo.


1 Answers

Even though help local doesn't mention it in Bash 3.x, local can accept the same options as declare (as of at least Bash 4.3.30, this documentation oversight has been corrected).

Thus, you can simply do:

local -r var=val

That said, declare inside a function by default behaves the same as local, as @ruakh states in a comment, so your 1st attempt should also have succeeded in creating a local read-only variable.

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


Thanks, Taylor Edmiston:

help declare shows all options support by both declare and local.

like image 95
mklement0 Avatar answered Sep 18 '22 19:09

mklement0