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

  • When you write name="Alex", Bash stores this in its internal variable table for the current shell session. No $ is used during assignment — only when you want to retrieve the value.
  • $variable triggers parameter expansion, where Bash replaces the reference with its stored string value before executing the rest of the line.
  • export marks a variable so that when Bash creates a child process (like running another script or command), it copies that variable into the new process’s environment block, which is how child processes gain access to it.
  • local inside a function creates a variable scoped to that function’s execution context; once the function returns, the variable and its value are discarded.
  • Arrays in Bash are stored as indexed lists internally, with ${array[@]} expanding to each element as a separate word (important for proper looping and quoting).

Real-World Use Cases

  • Configuration scripts:
export DB_HOST="localhost"
export DB_PORT="5432"
  • Dynamic file naming:
timestamp=$(date +%Y%m%d_%H%M%S)
backup_file="backup_$timestamp.tar.gz"
tar -czf "$backup_file" /data
  • Storing a list of servers for iteration:
servers=("web1" "web2" "db1")
for server in "${servers[@]}"
do
    ssh "$server" "uptime"
done

Best Practices

  • Use descriptive variable names (user_count instead of uc).
  • Always quote variables when using them ("$var") to avoid word-splitting and globbing issues.
  • Use local inside functions to avoid accidentally overwriting global variables.
  • Use uppercase names for environment/exported variables (DB_HOST) and lowercase for local/internal ones — a common convention that makes scripts easier to read.

Security Considerations

  • Avoid storing sensitive data like passwords directly in plain variables that might get logged or printed accidentally.
  • Be careful exporting variables that contain sensitive data, since child processes (and anything they log) will have access to them.
  • Never use eval on variables built from unsanitized user input.

Optimization Tips

  • Prefer arrays over creating many separate similarly-named variables (server1, server2, server3) — arrays are easier to loop through and maintain.
  • Use readonly for constants to catch accidental reassignment bugs early.
  • Avoid unnecessary subshells ($(...)) when a direct variable reference would do, since subshells have a small performance cost.

Troubleshooting Common Issues

  • “command not found” after assignment — usually caused by spaces around =, e.g., name = "Alex" is invalid; it must be name="Alex".
  • Variable appears empty — check if it was set inside a subshell (like a piped while loop) where changes don’t persist outside.
  • Exported variable not visible in child script — confirm you used export and that the child script is actually a separate process, not sourced.

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

  • Adding spaces around = during assignment.
  • Forgetting to quote variables, causing word-splitting bugs with values containing spaces.
  • Confusing $* and $@ when working with multiple arguments.
  • Not using local in functions, leading to accidental overwrites of global variables.

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

Total
2
Shares

Leave a Reply

Previous Post
How to Comment Your Bash Script

How to Comment Your Bash Script

Next Post
How to Perform Arithmetic in Bash

How to Perform Arithmetic in Bash

Related Posts