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:
Syntax
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
#!/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"
Login to try C/C++/Java/PHP code in the editor
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
- Trying to change or
unsetareadonlyvariable, which gives an error. - Expecting
readonlyto make the variable available to child processes, which needsexport. - Declaring a variable
readonlybefore assigning its final value, so it cannot be set later.
🔒
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first: