Menu
Coddy logo textTech

Variables In Scripts

Part of the Fundamentals section of Coddy's Terminal journey — lesson 68 of 82.

Variables make your scripts flexible and reusable. Instead of hardcoding values, you can store them in variables and reference them throughout your script.

To create a variable inside a script, use the same syntax you learned for the terminal: no spaces around the equals sign. To use the variable's value, prefix its name with a dollar sign:

#!/bin/bash
greeting="Hello"
name="World"
echo "$greeting, $name!"

This script outputs Hello, World!. The variables greeting and name store text that gets substituted when the script runs.

Variables become especially useful when you need to use the same value multiple times. If you reference a file path in several places, storing it in a variable means you only need to change it once:

#!/bin/bash
backup_dir="/home/user/backups"
echo "Creating backup in $backup_dir"
mkdir -p "$backup_dir"

Notice the quotes around "$backup_dir". Wrapping variables in double quotes is good practice because it handles paths or values that contain spaces correctly. Without quotes, a path like /my documents would break your command.

Variables in scripts work just like in the terminal, but they exist only while the script runs. Once the script finishes, those variables disappear.

challenge icon

Challenge

Easy

Create a shell script called intro.sh that uses variables to display a personalized message.

Your script should:

  1. Start with the shebang line (#!/bin/bash)
  2. Create a variable called language with the value Bash
  3. Create a variable called skill with the value scripting
  4. Use echo to print both variables in the format: Learning Bash scripting!

Make the script executable and run it. Your output should be:

Learning Bash scripting!

Hint: Create the script using echo with redirection. Remember to reference variables with $ in your echo statement, like echo "Learning $language $skill!"

Cheat sheet

Variables in Bash scripts store values that can be referenced throughout the script. Create variables without spaces around the equals sign, and access their values by prefixing the variable name with $:

#!/bin/bash
greeting="Hello"
name="World"
echo "$greeting, $name!"

Always wrap variables in double quotes to handle values with spaces correctly:

backup_dir="/home/user/backups"
echo "Creating backup in $backup_dir"
mkdir -p "$backup_dir"

Variables exist only while the script runs and disappear when it finishes.

Try it yourself

Terminal
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals