• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer navigation

The Geek Diary

  • OS
    • Linux
    • CentOS/RHEL
    • Solaris
    • Oracle Linux
    • VCS
  • Interview Questions
  • Database
    • oracle
    • oracle 12c
    • ASM
    • mysql
    • MariaDB
  • DevOps
    • Docker
    • Shell Scripting
  • Big Data
    • Hadoop
    • Cloudera
    • Hortonworks HDP

How to Make a Variable read-only (constant) in Bash and Korn Shell

by admin

Creating Bourne Shell Constants

A variable can be made read-only with the following syntax:

readonly var[=value]

The square brackets around =value mean that the assignment of a value is not always necessary. For instance, if the variable had previously been created and assigned a value, and you now want to make it read-only (and not change its current value), do not use =value.

If the variable did not previously exist, and you make it read-only, you may never assign a value to the variable. The value of a read-only variable cannot be changed. This is why read-only variables are referred to as constants:

$ sh
$ var=constant
$ readonly var
$ unset var 
var: is read only
$ var=new_value 
var: is read only

Creating Korn Shell Constants

A variable can be made read-only by using either of the following syntaxes:

typeset -r var[=value] 
readonly var[=value]

The following is a Korn shell example:

$ ksh
$ typeset -r cvar=constant
$ unset cvar 
ksh: cvar: is read only
$ cvar=new_value 
ksh: cvar: is read only

Filed Under: DevOps, Shell Scripting

Some more articles you might also be interested in …

  1. How to use “break” and “continue” statements in shell scripts
  2. Strings and Variables in Python
  3. ‘docker images’ command error – “Permission Denied”
  4. The Ultimate Guide To Use VS Code With Windows Subsystem for Linux (WSL)
  5. How to Pause and Resume Docker Containers
  6. Understanding Variables in Bash Shell Under Linux
  7. Puppet Server’s Resources Cheat Sheet with Examples
  8. How to use shell aliases in Linux
  9. How to Map Static IP to your Domain (with GoDaddy example)
  10. ansible-playbook: command not found

You May Also Like

Primary Sidebar

Recent Posts

  • qsub Command Examples in Linux
  • qsub: command not found
  • qrcp Command Examples in Linux
  • qmrestore Command Examples in Linux

© 2023 · The Geek Diary

  • Archives
  • Contact Us
  • Copyright