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

readonly Variables

In this page:

  1. readonly Variables

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"

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.