Discussion:
[Help-bash] Is `readonly` too strict?
Peng Yu
2018-02-22 06:58:09 UTC
Permalink
Hi,

Running `main.sh` shows an error. But `x` is set for `script.sh` not
`main.sh`. So I think that there should not be an error message. Is
`readonly` interpreted too strictly in bash?

$ cat main.sh
#!/usr/bin/env bash
# vim: set noexpandtab tabstop=2:

set -v
readonly x
x=abc ./script.sh

$ cat script.sh
#!/usr/bin/env bash
# vim: set noexpandtab tabstop=2:

echo "$x"
$ ./main.sh
readonly x
x=abc ./script.sh
./main.sh: line 6: x: readonly variable
--
Regards,
Peng
Greg Wooledge
2018-02-22 13:31:16 UTC
Permalink
Post by Peng Yu
So I think that there should not be an error message. Is
`readonly` interpreted too strictly in bash?
readonly is a large hammer that dumb sysadmins use to try to set up
a "restricted shell" environment. (You may laugh now.)

The use of readonly in a script means you are attempting to use a
large hammer to beat the variable into submission. Any attempt
to modify the variable IN ANY CONTEXT, PERIOD, will be met with the
hammer.
Post by Peng Yu
$ cat main.sh
#!/usr/bin/env bash
set -v
readonly x
x=abc ./script.sh
You are attempting to modify the value of x in the temporary execution
environment that is constructed for running the child program. But x
is already marked as readonly. So you can't modify it. HAMMER TIME.

Want to cheat the hammer? Try it this way:

env x=abc ./script.sh

Now continue laughing at how dumb you have to be to try to set up a
"restricted shell" environment.

Meanwhile, don't use readonly in your scripts. It's dumb.
Chet Ramey
2018-02-22 15:42:03 UTC
Permalink
Post by Peng Yu
Hi,
Running `main.sh` shows an error. But `x` is set for `script.sh` not
`main.sh`. So I think that there should not be an error message. Is
`readonly` interpreted too strictly in bash?
No. Posix has this to say when discussing variable assignments that precede
a simple command:

"If any of the variable assignments attempt to assign a value to a variable
for which the readonly attribute is set in the current shell environment
(regardless of whether the assignment is made in that environment), a
variable assignment error shall occur."

http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_09_01
--
``The lyf so short, the craft so long to lerne.'' - Chaucer
``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, UTech, CWRU ***@case.edu http://tiswww.cwru.edu/~chet/
Loading...