Yesterday I’ve discovered that Bash provides a means to mark variables as read-only, using the readonly keyword:
readonly hello="hello"
hello="world" # error message, Bash refuses to reassign the variable
This seems like a nice feature, still, I’ve never seen this used in any Bash script. Is there any reason not to use this extensivly? Is it actually portable?
readonlyis useful for some variables that are set by bash, for example$UID– non-readonly values like$LOGNAMEand$USERare easy for the user to alter.If you find
readonlyuseful then use it! Not many people usereadonly, but don’t let that bother you. Downside – like other variable attributes,readonlyattribute is not passed on with an exported variable, unless the child process is another bash.One use of
readonlyis to apply it to a function. That’s not widely done, but it solves a support issue of (by mistake) having two functions of the same name, which can be an issue when using functions stored outside the script.ksh also supports
readonly(as an alias).