Create the constants variable

From Linux Bash Shell Scripting Tutorial Wiki
Jump to navigation Jump to search

← Create an integer variableHomeBash variable existence check →

  • You can create the constants variables using the readonly command or declare command.
  • This will mark shell variables as unchangeable.
  • The readonly buitin syntax is as follows:
readonly var
readonly varName=value
  • The declare builtin syntax is as follows:
declare -r var
declare -r varName=value

Example

  • Create a constant variable called DATA and make its value always the same throughout the shell script i.e. it can't be changed:
readonly DATA=/home/sales/data/feb09.dat
echo "$DATA"

Here is what it prints:

/home/sales/data/feb09.dat

Now try to change it. For example:

DATA=/tmp/foo

You will get the following message:

bash: DATA: readonly variable
  • You cannnot unset (delete) the readonly variable. For example:
unset DATA

Sample outputs:

bash: unset: DATA: cannot unset: readonly variable

← Create an integer variableHomeBash variable existence check →