Harness the Combinatoric Power of Command-Line Tools and Utilities

Bash Basics

Lesson 2 - Variables

Bash

Variables let you store data for later use. In Bash, you create a variable by assigning a value to a name.

Creating Variables

To create a variable, use the = operator with no spaces:

name="World"
echo "Hello, $name!"

Notice that you use $name to access the value of the variable.

Variable Rules

  • No spaces around the = sign
  • Variable names are case-sensitive
  • Use $ to reference a variable’s value

Your Turn

Create a variable called greeting and print its value to the screen with echo:

greeting="Hi there"
echo $greeting

Environment Variables

Bash also has built-in environment variables. Try these:

echo "Your shell is: $SHELL"
echo "Your home directory is: $HOME"

You can get a list of your environment variables using the printenv command.

printenv

What You Learned

  • Variables store data using name=value syntax
  • Access variable values with $name
  • Environment variables provide system information