Setting variables as "readonly"

You can also set variables to be read-only, meaning they can't be changed.

readonly MAX=10

Set the variable called MAX to the value of 10, then you tried:


the shell would give the error:

bash: MAX: readonly variable

For the simple reason, that by saying something is readonly, you cannot change it afterwards. The only way to undo the readonly, is to kill the shell.

Once you've made a variable readonly, you can't even unset it

unset variablename

is the syntax to unset a variable

unset MAX

the shell will give another error:

bash: unset: MAX: cannot unset: readonly variable

So readonly is a way to create a readonly variable - no rocket science there.


Set a variable POPPINS, and then perform the following parameter substitutions. Obviously try to get the answers BEFORE heading for you Linux machine.

  1. POPPINS='supercalifragilisticexpialidocious'

    1. echo ${POPPINS:=Mary was here}

    2. echo ${POPPINS%a*}

    3. unset POPPINS; echo ${POPPINS:-JulieAndrews}

  2. POPPINS='supercalifragilisticexpialidocious'; echo ${POPPINS#s??e}

    1. echo ${POPPINS%%f*s}

    2. echo ${POPPINS%c*s}

    3. echo ${POPPINS:6:10}

    4. echo ${#POPPINS}

Challenge sequences:

What do these produce and why?

  1. echo ${POPPINS/f*c/BLAAH}

  2. echo ${POPPINS/%c*s/BLAAH}

  3. echo ${POPPINS/#c*s/BLAAH}

  4. echo ${POPPINS/#s*c/BLAAH}