Search code examples
bash

Test if a variable is read-only


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?


Solution

  • 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.