0
0
Bash Scriptingscripting~20 mins

Read-only variables (readonly) in Bash Scripting - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Readonly Variable Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate
2:00remaining
What is the output of this Bash script using readonly?
Consider this Bash script:
readonly VAR=10
VAR=20
echo $VAR

What will be the output when you run it?
Bash Scripting
readonly VAR=10
VAR=20
echo $VAR
A10
B20
Cbash: VAR: readonly variable
DEmpty output
Attempts:
2 left
💡 Hint
readonly variables cannot be changed after being set.
💻 Command Output
intermediate
2:00remaining
What happens when you unset a readonly variable in Bash?
Given this script:
readonly MYVAR=5
unset MYVAR
echo $MYVAR

What will be the output or error?
Bash Scripting
readonly MYVAR=5
unset MYVAR
echo $MYVAR
A5
Bbash: unset: MYVAR: cannot unset: readonly variable
CEmpty output
Dbash: MYVAR: unbound variable
Attempts:
2 left
💡 Hint
readonly variables cannot be unset.
📝 Syntax
advanced
2:00remaining
Which option correctly declares a readonly variable with value 'hello' in Bash?
Choose the correct syntax to declare a readonly variable GREETING with value 'hello'.
Areadonly GREETING:='hello'
Breadonly GREETING=hello
Creadonly 'GREETING=hello'
Dreadonly GREETING='hello'
Attempts:
2 left
💡 Hint
Use the readonly command followed by variable assignment without quotes around the whole expression.
🚀 Application
advanced
2:00remaining
How to protect a variable from accidental changes in a Bash script?
You want to make sure a variable CONFIG_PATH cannot be changed later in your script. Which approach achieves this?
ASet CONFIG_PATH and then run: readonly CONFIG_PATH
BSet CONFIG_PATH and then run: export CONFIG_PATH
CSet CONFIG_PATH and then run: unset CONFIG_PATH
DSet CONFIG_PATH and then run: declare -i CONFIG_PATH
Attempts:
2 left
💡 Hint
readonly prevents reassignment, export shares variable with child processes.
🔧 Debug
expert
2:00remaining
Why does this Bash script fail to protect the variable with readonly?
Look at this script:
CONFIG=default
readonly CONFIG
CONFIG=custom
echo $CONFIG

Why does it not prevent changing CONFIG?
Bash Scripting
CONFIG=default
readonly CONFIG
CONFIG=custom
echo $CONFIG
Areadonly was set without assigning a value, so CONFIG remains changeable
Breadonly only works on exported variables
CCONFIG=custom is ignored silently by Bash
Dreadonly must be declared before any assignment
Attempts:
2 left
💡 Hint
readonly without assignment locks current value, but here it was declared after assignment.