In bash, what is the difference in declare -r and readonly?
$ declare -r a="a1" $ readonly b="b1" I'm not sure which to choose.
Note: readonly is a "Special Builtin". If Bash is in POSIX mode then readonly (and not declare ) has the effect "returning an error status will not cause the shell to exit".
'declare' is a bash built-in command that allows you to update attributes applied to variables within the scope of your shell. In addition, it can be used to declare a variable in longhand. Lastly, it allows you to peek into variables.
In Bash scripting, the “read” command is used to obtain input from users. Understanding the “read” command is key to making your code more interactive. The “read” command is used to obtain inputted information from the user.
$* Stores all the arguments that were entered on the command line ($1 $2 ...). "$@" Stores all the arguments that were entered on the command line, individually quoted ("$1" "$2" ...).
tl;dr readonly uses the default scope of global even inside functions. declare uses scope local when in a function (unless declare -g).
At first glance, no difference.
Examining using declare -p
$ declare -r a=a1 $ readonly b=b1 $ declare -p a b declare -r a="a1" declare -r b="b1" # variable a and variable b are the same Now review the difference when defined within a function
# define variables inside function A $ function A() { declare -r x=x1 readonly y=y1 declare -p x y } $ A declare -r x="x1" declare -r y="y1" # ***calling function A again will incur an error because variable y # was defined using readonly so y is in the global scope*** $ A -bash: y: readonly variable declare -r x="x1" declare -r y="y1" # after call of function A, the variable y is still defined $ declare -p x y bash: declare: x: not found declare -r y="y1" To add more nuance, readonly may be used to change a locally declared variable property to readonly, not affecting scope.
$ function A() { declare a="a1" declare -p a readonly a declare -p a } $ A declare -- a="a1" declare -r a="a1" $ declare -p a -bash: declare: a: not found 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". If Bash is in POSIX mode then readonly (and not declare) has the effect "returning an error status will not cause the shell to exit".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With