LinuxCommandLibrary

readonly

Mark shell variables as read-only

TLDR

Make variable readonly
$ readonly [VAR]="[value]"
copy
Make existing variable readonly
$ readonly [VAR]
copy
List readonly variables
$ readonly
copy
Make function readonly
$ readonly -f [function_name]
copy
Make array readonly
$ readonly -a [ARRAY]
copy

SYNOPSIS

readonly [options] [name[=value]...]

DESCRIPTION

readonly is a shell builtin that marks variables or functions as read-only, preventing modification or unsetting. Useful for constants and protecting configuration values.

PARAMETERS

-p

Print readonly variables.
-f
Make functions readonly.
-a
Make arrays readonly.
-A
Make associative arrays readonly.

EXAMPLES

$ # Create readonly variable
readonly PI=3.14159

# Attempting to change fails
PI=3  # bash: PI: readonly variable

# Make existing readonly
CONFIG_FILE="/etc/app.conf"
readonly CONFIG_FILE

# Readonly function
myfunc() { echo "Hello"; }
readonly -f myfunc

# List all readonly
readonly -p

# Readonly array
readonly -a COLORS=("red" "green" "blue")
copy

IN SCRIPTS

$ #!/bin/bash
readonly SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
readonly CONFIG="${SCRIPT_DIR}/config.ini"
readonly VERSION="1.0.0"
copy

CAVEATS

Cannot unset readonly variables (until shell exits). Subshells don't inherit readonly status. Bash specific.

HISTORY

readonly is a POSIX shell builtin, with extended options in bash and other modern shells.

SEE ALSO

declare(1), export(1), typeset(1), bash(1)

> TERMINAL_GEAR

Curated for the Linux community

Copied to clipboard