Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if a variable is read-only

Tags:

bash

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?

like image 945
l0b0 Avatar asked Dec 21 '22 20:12

l0b0


2 Answers

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.

like image 143
plundra Avatar answered Jan 02 '23 10:01

plundra


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; }
like image 32
PJ Eby Avatar answered Jan 02 '23 10:01

PJ Eby