Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of read-only variables in shell scripts [closed]

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.

like image 576
user1812379 Avatar asked Nov 15 '12 19:11

user1812379


People also ask

What is readonly variable in shell?

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"

How do I get rid of readonly variables?

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.

How do I remove a read-only variable in Linux?

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.

Which type of variable we Cannot unset in shell script?

Explanation: We cannot use the unset command to unset variables that are marked readonly.


2 Answers

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
$ 
like image 114
Mark Reed Avatar answered Nov 15 '22 19:11

Mark Reed


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
like image 29
JRFerguson Avatar answered Nov 15 '22 20:11

JRFerguson