Using read-only variables in shell scripts

Is it good practice to program shells to use read-only variables when possible, or have any flaws? For example. if I wanted to write several scripts consisting of several script files that use immutable file paths, it would be advisable to declare such paths:

readonly LOGS export LOGS LOGS="/some/path" 

Another question: is it useful to separate the monolithic and tedious too read shell script code in separate files? Thanks so much for your answers.

+7
source share
4 answers

Sounds like you think readonly does more than it really does. Firstly, readonly status is not exported to 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 $ 
+11
source

Generally speaking, using read-only variables (in any language) and modulating your program (in any language) is good.

Read-only variables protect against a common source of errors and also help improve readability and maintainability. Knowing that you can rely on the value of a variable allows you to better reason about your program and make assumptions about that variable later β€” things you could not do if the variable were mutable.

Modulation improves maintainability and reuse. More modules usually mean finer-grained units that can be reused in different circumstances, a shorter code that is easier to read, and if your modules are independent, less interaction between parts that can destroy the modification.

+5
source

The classic use of read-only variables with TMOUT . Setting this variable to a non-zero value will exit the interactive terminal session after TMOUT seconds of inactivity (i.e., Keyboard input). To defeat a smart user from overriding a parameter, use readonly :

 readonly TMOUT=60 

Having done this, it will not work:

 export TMOUT=0 
+5
source

I don't think readonly variables in bash are useful. I cannot think of any problem that I saw that could have been prevented by making the variable readonly. Such restrictions contradict the dynamic nature of bash. There are other most common causes of problems (for example, incorrect or forgetting to declare variables as local), which in any case cannot be prevented.

If you want to separate things, try to separate only "functions", not just pieces of code. It’s easier to repeat the use of a small thing if you know that "source ~ / myscript.sh" does not actually do anything.

+2
source

All Articles