← Back to Bash Course | Chapter 2: Variables & Types | Lesson 7 of 13

readonly Variables

A readonly variable is like writing in permanent marker instead of pencil: once it is written you cannot erase or change it, and the computer complains if you try.

In this page:

  1. readonly Variables
Syntax
bash
readonly VARIABLE_NAME=value

readonly Variables

Marking a variable readonly prevents it from being reassigned later in the script, causing an error if something tries to change it. This is useful for constants that should never be accidentally overwritten.

Once set readonly, a variable stays that way for the rest of the script's execution.

Warning: Attempting to reassign a readonly variable does not silently fail — it prints an error to stderr.

Example: readonly Variables

bash
#!/bin/bash
readonly PI=3.14159
echo "Pi is $PI"

PI=3.14  # this will produce an error
echo "This line may not run depending on the shell"
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Trying to change or unset a readonly variable, which gives an error.
  2. Expecting readonly to make the variable available to child processes, which needs export.
  3. Declaring a variable readonly before assigning its final value, so it cannot be set later.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.