Learn/Bash/2. Variables and read
Lesson 2 of 8
Sign in

Bash, lesson 2

Variables and read

Creating variables

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.

Exercise 1

Greeting card

Press Ctrl Enter or Check to test your code.

Exercise 2

Name badge

Press Ctrl Enter or Check to test your code.

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).

Using variables

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.

Constants

Mark a variable read-only with readonly (or declare -r). Changing it afterwards is an error:

Reading input with read

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 substitution

$(command) runs a command and inserts its output. It is how you capture results in a variable:

Further reading

  • Bash manual: Shell parameters
  • Bash manual: Shell parameter expansion
  • Bash manual: Bash builtins (read, readonly)

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=3
fruit="apple"
echo "I like $fruit"            # I like apple
echo "Two ${fruit}s, please"    # Two apples, please ($fruits would be empty)
readonly max_users=10
read -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 mathematician
today=$(date +%Y-%m-%d)
echo "Today is $today"
Dear NAME,
Greetings from CITY!
Ada
Rome
Dear Ada,
Greetings from Rome!
LAST, FIRST
Role: JOB TITLE
Ada Lovelace Chief Analyst
Lovelace, Ada
Role: Chief Analyst