#Bash 的 readonly 命令
readonly [OPTION]... NAME[=VALUE]...
功能
定义局部变量。
类型
Bash 内置命令。
参数
OPTION选项:-a- 变量是索引数组变量-A- 变量是关联数组变量-f- 变量是函数-p- 打印所有只读变量
NAME- 变量名VALUE- 变量的值
#示例
查看只读变量
$ readonly -p
declare -ar BASH_VERSINFO=([0]="5" [1]="2" [2]="21" [3]="1" [4]="release" [5]="x86_64-pc-linux-gnu")
declare -ir EUID="1000"
declare -ir UID="1000"
定义只读变量
$ readonly X=10 # 定义只读变量
$ X=20 # 尝试修改,报错
-bash: X: readonly variable
$ Y=30 # 定义普通变量
$ readonly Y # 将变量设为只读
$ Y=40 # 尝试修改,报错
-bash: Y: readonly variable
#相关命令
| 命令 | 说明 |
|---|---|
| declare | 声明变量并设置属性 |
#手册
readonly: readonly [-aAf] [name[=value] ...] or readonly -p
Mark shell variables as unchangeable.
Mark each NAME as read-only; the values of these NAMEs may not be
changed by subsequent assignment. If VALUE is supplied, assign VALUE
before marking as read-only.
Options:
-a refer to indexed array variables
-A refer to associative array variables
-f refer to shell functions
-p display a list of all readonly variables or functions,
depending on whether or not the -f option is given
An argument of `--' disables further option processing.
Exit Status:
Returns success unless an invalid option is given or NAME is invalid.