Sunday, March 23, 2008

Constant As a Northern Star: Read-only Variables in Bash

I didn't know bash had read-only variables.

I found out by peeking at the code for s3-bash.

Well, I guess I did know, since I can't make assignments to variables like $1, or $UID. I just didn't know I could create them. Well, I can.
$ PI=3.14159
$ echo $PI
3.14159
$ PI=3
$ echo $PI
3
$ readonly PI=3.14159
$ PI=3.14159
$ echo $PI
3.14159
$ PI=3
./constant: line 11: PI: readonly variable
$ echo $PI
3.14159
Caveat programmor: In a scripts, they're great for creating constants; however, once you make a variable readonly, there's no way to change it back to read/write. If you make a variable readonly in an interactive shell, you have to exit the shell to get rid of it.

"Adult supervision required. Don't try this at home, kids."

No comments: