Shell Variables
A variable stores text under a name. The shell keeps the text until the variable is removed or the shell closes.
Store and print
name=Ana stores Ana, and echo $name prints it.
name=Ana
echo $nameChange the value
A second assignment replaces the old text.
name=Ana
name=Bo
echo $nameRemove a variable
unset removes the variable, so echo prints an empty line.
name=Ana
unset name
echo $nameUse a variable in a line
The shell fills $greeting in before echo prints the line.
greeting=Hello
echo $greeting AnaExample
name=Ana
city=Leeds
echo $name lives in $cityKey points
- Use name=value to store text in a variable.
- Write name=value with no spaces around the = sign.
- Use echo $name to print the text stored in a variable.
- Use unset name to remove a variable.
- A variable holds text, and the shell reads it back with $ and the name.
In this example, two assignments store Ana and Leeds. Then echo prints a line, and the shell fills in both variables.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which line stores the text Ana in a variable called name?