LESSON · 1 OF 5

Declaring and expanding variables

Declaring and expanding variables

A variable in bash is a named container for a string. Bash treats everything as a string by default. Numbers, paths, booleans, all strings until you tell bash otherwise.

Assignment

bash
name=alice
count=5
message="hello world"

Three rules that trip up almost every beginner:

  1. No spaces around =. name = alice is wrong. Bash reads that as "run the command name with arguments = and alice".
  2. Quote values containing spaces. msg=hello world fails, msg="hello world" works. More on quoting next.
  3. Lowercase for your variables. Convention: uppercase for exported environment variables (PATH, HOME), lowercase for local script variables. This isn't enforced by bash, it's how you avoid clobbering system variables by accident.

Expansion

Use a variable's value with $:

bash
name=alice
echo $name              # alice
echo "hello, $name"     # hello, alice

The longer form ${name} does the same thing but with explicit boundaries. You need it when the variable name butts up against other characters:

bash
file=report
echo $file_final        # wrong: bash looks for a variable called "file_final"
echo ${file}_final      # right: prints "report_final"

No type declarations

You don't declare a variable before using it. Assign, then use.

bash
first_name=Alice
last_name=Smith
full_name="$first_name $last_name"
echo "$full_name"

Four lines, no boilerplate, and the shape of every script you'll ever write.

Spin up a fresh environment and practice live.
linux-devops-basic · fresh machine · ready in under a minute