如何制作"只读变量"?

rub*_*nvb 6 shell posix sh

在Bash中,您可以创建只读变量

declare -r somevar='bla'
Run Code Online (Sandbox Code Playgroud)

我试图在POSIX中找到类似的东西sh,但唯一接近的是set文档中的这句话:

[...]只读变量无法重置.

如何创建这样的只读变量?

fed*_*qui 7

你可以利用readonly:

$ var="hello"
$ readonly var
$ echo $var
hello
$ var="bye"
sh: var: readonly variable
Run Code Online (Sandbox Code Playgroud)

  • 我也找到了[这个](https://wiki.ubuntu.com/DashAsBinSh#declare_or_typeset),但无法在 POSIX 规范中找到它。因此我相信它也是一个延伸。我可以看到它[不存在于某些 shell 中](http://hyperpolyglot.org/unix-shells#variables)。 (2认同)