Defining constants in bash scripts

If you are coming from a different programming language you are probably familiar to the concept of constants already. A constant is just like a variable except for the fact that its value does not change during the execution of your script.

This makes sense in scripts for which you have to define the total amount of months in a year for example. This is a number that is not likely to change anytime soon.


As you might have noticed the TOTAL_MONTHS constant is written in all caps, this is actually just a convention and nothing prevents you from changing its value. Using all caps does not enforce a readonly value in bash so if you would like to change TOTAL_MONTHS to 11 you are free to do so:


Your shell doesn’t complain at all about this as you see.

This all caps convention is consistent with how environment variables and shell variables are defined. An example of an environment variable would be $PATH.

Enforcing read only values

If you need to enforce a readonly value you may do so by using the declare or readonly commands. These two commands work very similar but differ in the default scope for which the variables are available. The readonly command defaults to a global scope where declare uses a local scope by default.

The following snippet illustrates what happens when you try to reassign a readonly variable.

$ declare -r TOTAL_MONTHS="12"
$ declare -r TOTAL_MONTHS="11"
bash: declare: TOTAL_MONTHS: readonly variable

See Also

6 Non-Programming Books for Programmers