How to Use Variables in Bash

How to Use Variables in Bash

How to Use Variables in Bash

Variables are the very first thing I teach anyone starting with Bash scripting, because almost nothing meaningful can be built without them. They let you store data, reuse values, and make your scripts dynamic instead of hardcoded. In this guide, I’ll cover everything from declaring a simple variable to working with arrays, environment variables, and special built-in variables.

What Is a Variable in Bash?

A variable is simply a name that holds a value. Unlike many programming languages, Bash doesn’t require you to declare a data type — everything is treated as a string by default, though Bash will interpret numeric-looking strings as numbers when used in an arithmetic context.

Declaring and Using Variables

Basic Syntax

variable_name=value

There must be no spaces around the = sign — this is one of the most common beginner mistakes.

Example 1: Simple Variable Assignment

#!/bin/bash

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

Output:

Hello, Alex!

Example 2: Using Curly Braces

Curly braces help Bash clearly identify where a variable name starts and ends, especially when it’s next to other text.

#!/bin/bash

fruit="apple"
echo "I have a ${fruit}pie"

Output:

I have a applepie

Without the braces ($fruitpie), Bash would try to find a variable literally named fruitpie, which doesn’t exist, and print nothing.

Example 3: Numeric Variables

#!/bin/bash

age=25
echo "You are $age years old"

Output:

You are 25 years old

Even though age looks numeric, it’s still stored as a string internally — Bash only treats it as a number when used inside an arithmetic context like $(( )).

Command Substitution: Storing Command Output in a Variable

One of the most useful variable patterns is capturing the output of a command.

#!/bin/bash

current_date=$(date)
echo "Today is: $current_date"

Output:

Today is: Tue Jul 28 14:32:10 UTC 2026

The $( ) syntax runs the enclosed command and substitutes its standard output into the variable.

Read-Only Variables

You can make a variable constant using readonly, which prevents it from being changed later in the script.

#!/bin/bash

readonly PI=3.14159
echo "The value of PI is $PI"

PI=3.14  # This will cause an error

Output:

The value of PI is 3.14159
bash: PI: readonly variable

Unsetting a Variable

If you want to remove a variable entirely, use unset.

#!/bin/bash

greeting="Hello"
echo "$greeting"

unset greeting
echo "After unset: $greeting"

Output:

Hello
After unset: 

Variable Scope: Local vs Global

By default, variables in Bash are global to the script (and any functions called within it). Inside a function, you can use local to restrict a variable’s scope.

#!/bin/bash

my_function() {
    local local_var="I am local"
    global_var="I am global"
    echo "Inside function: $local_var"
}

my_function
echo "Outside function: $global_var"
echo "Outside function: $local_var"

Output:

Inside function: I am local
Outside function: I am global
Outside function: 

Notice local_var isn’t accessible outside the function, while global_var is — this is an important distinction when writing scripts with multiple functions.

Environment Variables

Environment variables are variables that are available to the shell and any child processes it starts. Bash comes with several built-in ones.

#!/bin/bash

echo "Your username is: $USER"
echo "Your home directory is: $HOME"
echo "Your current shell is: $SHELL"
echo "Current working directory: $PWD"

Sample output:

Your username is: alex
Your home directory is: /home/alex
Your current shell is: /bin/bash
Current working directory: /home/alex/scripts

Exporting a Custom Variable

By default, a variable you create is only visible in your current shell, not in child processes. Use export to make it available to any programs your script launches.

#!/bin/bash

export APP_ENV="production"
./another_script.sh

Inside another_script.sh, $APP_ENV would now be accessible because it was exported.

Special Bash Variables

Bash provides several built-in variables that carry useful information automatically:

VariableMeaning
$0Name of the script
$1, $2, …Positional arguments passed to the script
$#Number of arguments passed
$@All arguments as separate words
$*All arguments as a single string
$$Process ID of the current script
$?Exit status of the last executed command

Example: Using Special Variables

#!/bin/bash

echo "Script name: $0"
echo "Number of arguments: $#"
echo "All arguments: $@"
echo "Process ID: $$"

ls /nonexistent-folder
echo "Exit status of last command: $?"

Sample run:

$ ./script.sh one two three
Script name: ./script.sh
Number of arguments: 3
All arguments: one two three
Process ID: 24810
ls: cannot access '/nonexistent-folder': No such file or directory
Exit status of last command: 2

Arrays in Bash

Bash supports one-dimensional arrays, which let you store multiple values under a single variable name.

Example: Declaring and Using an Array

#!/bin/bash

fruits=("apple" "banana" "mango")

echo "First fruit: ${fruits[0]}"
echo "All fruits: ${fruits[@]}"
echo "Number of fruits: ${#fruits[@]}"

Output:

First fruit: apple
All fruits: apple banana mango
Number of fruits: 3

Example: Looping Through an Array

#!/bin/bash

colors=("red" "green" "blue")

for color in "${colors[@]}"
do
    echo "Color: $color"
done

Output:

Color: red
Color: green
Color: blue

Associative Arrays (Bash 4+)

Bash also supports associative arrays (key-value pairs), similar to dictionaries in other languages.

#!/bin/bash

declare -A capitals
capitals[France]="Paris"
capitals[Japan]="Tokyo"
capitals[Egypt]="Cairo"

echo "The capital of Japan is ${capitals[Japan]}"

for country in "${!capitals[@]}"
do
    echo "$country -> ${capitals[$country]}"
done

Output:

The capital of Japan is Tokyo
France -> Paris
Japan -> Tokyo
Egypt -> Cairo

How This Works Internally

Real-World Use Cases

export DB_HOST="localhost"
export DB_PORT="5432"
timestamp=$(date +%Y%m%d_%H%M%S)
backup_file="backup_$timestamp.tar.gz"
tar -czf "$backup_file" /data
servers=("web1" "web2" "db1")
for server in "${servers[@]}"
do
    ssh "$server" "uptime"
done

Best Practices

Security Considerations

Optimization Tips

Troubleshooting Common Issues

Frequently Asked Questions

Q: Do I need to declare a variable’s type in Bash? A: No. All variables are treated as strings by default; Bash converts them for arithmetic only when needed.

Q: What’s the difference between a local and global variable? A: Global variables are accessible throughout the script; local variables (declared with local inside a function) are only accessible within that function.

Q: How do I pass a variable to another script? A: Export it using export VAR_NAME=value before calling the other script, or pass it explicitly as a command-line argument.

Q: How do I check if a variable is empty? A: Use [ -z "$var" ], which returns true if the variable is empty or unset.

Common Mistakes to Avoid

Summary

Variables are the foundation of every Bash script — they store user input, command output, configuration values, and more. Once you’re comfortable with basic assignment, command substitution, environment variables, scope with local/export, and arrays, you’ll have everything you need to build dynamic, reusable scripts instead of static, one-off commands.

References

Exit mobile version