天道酬勤,学无止境

Test if a variable is read-only

Question

To test if a variable is read-only, there are the following ugly hacks:

# True if readonly
readonly -p | egrep "declare -[:lower:]+ ${var}="

# False if readonly
temp="$var"; eval $var=x 2>/dev/null && eval $var=\$temp

Is there a more elegant solution?

Answer1

Using a subshell seems to work. Both with local and exported variables.

$ foo=123
$ bar=456

$ readonly foo

$ echo $foo $bar
123 456

$ (unset foo 2> /dev/null) || echo "Read only"
Read only

$ (unset bar 2> /dev/null) || echo "Read only"
$

$ echo $foo $bar
123 456           # Still intact :-)

The important thing is that even is that the subshell salvages your RW ($bar in this case) from being unset in your current shell.

Tested with bash and ksh.

Answer2

You can also add an empty string to the variable, which still leaves its value alone, but is faster than using a subshell, e.g.:

foo+= 2>/dev/null || echo "Read only"

Captured as a function, it'd be:

is-writable() { eval "$1+=" >2/dev/null; }
标签

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

相关推荐