Is it good shell programming practice to use read-only variables whenever possible or does it have any drawbacks? E.g. if I wanted to write some script that consists of multiple script files that make use of immutable file paths, would it make sense to declare the paths like that:
readonly LOGS
export LOGS
LOGS="/some/path"
Another question: Is it a good idea to split monolithic and tedious too read shell script code into separate files? Many thanks for your answers.
Read-only Variables 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. For example, the following script generates an error while trying to change the value of NAME − #!/bin/sh NAME="Zara Ali" readonly NAME NAME="Qadiri"
For each name, remove the corresponding variable or function. If no options are supplied, or the -v option is given, each name refers to a shell variable. Read-only variables may not be unset. If -f is specifed, each name refers to a shell function, and the function definition is removed.
You can't delete mySite. The whole point of the readonly command is to make it final and permanent (until the shell process terminates). If you need to change a variable, don't mark it readonly.
Explanation: We cannot use the unset command to unset variables that are marked readonly.
It sounds like you might think that readonly
does more than it really does. For one thing, readonly status is not exported into the environment or inherited by child processes:
$ declare -rx LOGS=hello
$ LOGS=goodbye
bash: LOGS: readonly variable
$ bash -c 'echo "$LOGS"'
hello
$ bash -c 'LOGS=goodbye; echo "$LOGS"'
goodbye
$
A classic use of read-only variables is with TMOUT
. Setting this variable to a non-zero value will logout an interactive terminal session after TMOUT
seconds of inactivity (i.e. no keyboard input). To defeat a smart user from overriding the setting, use readonly
:
readonly TMOUT=60
Having done this, there is no way to do:
export TMOUT=0
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