Bash, lesson 2
A Bash variable is a name that holds a piece of text. Assign with =, and no spaces around
it:
That spacing rule surprises everyone once. city = "Lisbon" does not assign anything: Bash
reads it as "run a command called city with the arguments = and Lisbon" and fails with
command not found.
Names may contain letters, digits and underscores, and cannot start with a digit. By convention,
scripts use lowercase names for their own variables, because uppercase names like PATH,
HOME and USER are used by the system.
2 exercises to try what you just read.
Every Bash variable is, at heart, a string. count=3 stores the text 3; Bash only treats it
as a number when you do arithmetic (next lesson).
Put $ in front of the name to use its value. This is called expansion. Write ${name}
when the name is followed by characters that could be read as part of it:
Using a variable that was never set gives an empty string, not an error, so a typo in a name fails silently. Read your output carefully.
Always put expansions inside double quotes unless you have a reason not to. Unquoted, Bash
splits the value at spaces and may even treat * as a file pattern. "$name" passes the value
exactly as it is.
Mark a variable read-only with readonly (or declare -r). Changing it afterwards is an error:
read takes one line from standard input and stores it in a variable:
Always use -r. Without it, read treats backslashes in the input as special and removes them.
Give read several names and it splits the line into words at whitespace, one word per name.
Any extra words all go into the last name:
Each read consumes one line, so call it again for the next line. When there is no more input,
read fails (returns a non-zero exit status), which you will use in lesson 5 to loop over all
lines.
$(command) runs a command and inserts its output. It is how you capture results in a variable:
Read a name on the first line and a city on the second line. Print:
Sample input:
Sample output:
Names and cities may contain spaces (for example New York).
Read one line containing a first name, a last name and then a job title that may be several
words long, for example Ada Lovelace Chief Analyst. Print a badge:
Sample input:
Sample output:
city="Lisbon"
count=3fruit="apple"
echo "I like $fruit" # I like apple
echo "Two ${fruit}s, please" # Two apples, please ($fruits would be empty)readonly max_users=10read -r name
echo "Hello, $name!"# input: Ada Lovelace 1815
read -r first last year
echo "$last, born $year" # Lovelace, born 1815
# input: Ada Lovelace was a mathematician
read -r first rest
echo "$rest" # Lovelace was a mathematiciantoday=$(date +%Y-%m-%d)
echo "Today is $today"Dear NAME,
Greetings from CITY!Ada
RomeDear Ada,
Greetings from Rome!LAST, FIRST
Role: JOB TITLEAda Lovelace Chief AnalystLovelace, Ada
Role: Chief Analyst