Bash Variables
A variable is a named place that stores a value for later use. A script can read the value, change it, and read it again.
Spaces around = break assignment
Spaces around the equals sign make Bash treat the name as a command. That command does not exist, so the script fails with this real error.
name = "Sam"Create and read a variable
The first line stores Sam in the variable name. The echo line reads it back with $name.
name="Sam"
echo $nameChange a stored value
A second assignment replaces the old value. The first echo prints Paris and the second echo prints London.
city="Paris"
echo $city
city="London"
echo $cityExample
user_name="Ada"
score=10
echo $user_name
echo $score
score=20
echo $scoreKey points
- A variable stores one value under one name.
- Assignment writes a value with an equals sign and no spaces around it.
- Writing $ before a name reads the value stored in that variable.
- A later assignment replaces the value an earlier assignment stored.
- Variable names use letters, digits, and underscores.
- A variable name starts with a letter or an underscore, never a digit.
In this example, the first line stores Ada in the variable user_name. The second line stores 10 in the variable score. The next two echo lines read both values and print Ada and 10. The fifth line replaces the score with 20. The last echo line prints the new value, 20.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which line creates a variable named age that holds 12?