What are Bash variables and how to use them effectively
Bash variables are named storage units that hold data values for reference and manipulation within the Linux command line environment. In shell scripting, they allow users to pass dynamic information, such as file paths, configuration settings, or command outputs, without writing them directly into their code.
Here’s what you need to know about Bash variables:
- Assigning Bash variables. Use a key=value format without spaces around the equal sign. Values containing whitespaces should be enclosed in quotation marks.
- Different types of Bash variables. Set user-defined variables that are local to a particular script, or environment variables that are accessible to other processes within the same shell.
- Bash variables’ scope. Determine where the variables can be accessed. By default, they are global within a script, but adding the local keyword restricts them to specific functions.
- Special Bash variables. Use placeholders like $0, $$, and $? to automatically pass data, like script information, process IDs, and exit statuses, to your variables.
- Exporting and unsetting variables. Pass variables to a script’s child processes by exporting them. Meanwhile, remove variables from the shell memory with unset.
- Using quotes and command substitution. Use quotation marks and command substitution to control value interpretation. Single quotes preserve literal data, double quotes allow value expansion, while the $command captures command output as data.
- Common Bash variable use cases. Combine Bash variables with conditional statements, loops, and arrays to pass data dynamically, which is helpful for automated tasks.
Before getting into these detailed usages, let’s first learn the basics of assigning values to Bash variables.
How do you assign values to variables in Bash?
Assigning a value to a Bash variable relies on a strict syntax where the assignment operator (=) connects a name to a value.
The most important rule is that you must not place spaces around the assignment operator.
Otherwise, the shell incorrectly interprets the variable name as a command and the value as an argument, resulting in an error.
Direct assignment is the most fundamental method of defining a variable, where you explicitly map a static string to a variable name. This is typically used for setting constants or configuration paths that do not require dynamic computation.
#!/bin/bash server_name=Apache-01 echo $server_name

By default, Bash treats numeric values as character strings. However, the shell can interpret these strings as integers when they are used within specific arithmetic contexts written inside double parentheses ((example)) or with the expr command.
#!/bin/bash initial_value=10 (( result = initial_value + 5 )) echo $result
If you want to assign values that contain spaces or special characters, use quotation marks. Without them, Bash interprets the first word as the variable value and subsequent words as separate commands or arguments.
Wrapping the text in quotes ensures the shell treats the entire sequence as a single unit of data.
#!/bin/bash error_msg="File not found" echo $error_msg
To ensure variables are parsed correctly, you must adhere to specific naming conventions.
Their names can only contain alphanumeric characters and underscores and cannot begin with a number. Bash is also case-sensitive, meaning PATH, Path, and path represent three distinct variables.
What are the types of Bash variables?
Based on their accessibility and purpose within the system, variables in Bash are categorized into two types: user-defined and environment variables.
What are user-defined variables?
User-defined variables are custom identifiers that users create to store temporary data within a Bash script or terminal session. These variables are local to the process that created them and are only valid when the session or script runs.
You create them by simply assigning a value to a new name. For example:
#!/bin/bash app_dir="/var/www/html" echo "Deploying to: $app_dir"
In this Bash script example, the app_dir variable is only valid for this particular script and the echo command, meaning other processes can’t access it.
What are environment variables?
In Bash, environment variables are global settings whose data is accessible by accessible by child processes spawned from that shell. Since such variables are within the session, they can’t be used by other users or already-running programs.
Bash environment variables are set using the export command and conventionally use uppercase letters as their names. For example:
export VAR=value
If you write this script with the same user and shell, it will automatically inherit the VAR variable’s value:
#!/bin/bash echo "$VAR"
Here are some examples of Bash environment variables:
| Variable | Example | Function |
| SHELL | /bin/bash | Defines the name of the shell used |
| PWD | /root | Shows the current working directory |
| LOGNAME | root | Defines the logged-in user name |
| MOTD_SHOWN | pam | Defines the message of the day for the system |
| HOME | root | Home directory of the user |
| SSH_CONNECTION | 185.185.185.185 54321 185.185.185.186 12 | SSH connection information [user IP] [user port] [Linux machine IP] [Linux machine port] |
| TERM | xterm-256color | Defines the terminal type |
| USER | root | Name of the current user |
| SSH_CLIENT | 185.185.185.185 54321 12 | SSH client information [user IP] [user port] [Linux machine port] |
| PATH | /usr/local/sbin | Defines the directories that bash will search to find a command |
| SSH_TTY | /dev/pts/0=/usr/bin/printenv | Displays the path to the device associated with the current shell or command |
To check the environment variables in your system, use the printenv command. You can shorten the output by piping to less, like this:
printenv | less

How does variable scope work in Bash?
Variable scope defines the context in which a variable can be accessed or modified. It is crucial to prevent a variable in one function from accidentally overwriting data in the main script due to having the same name.
By default, all variables declared in a script are global, meaning they can be accessed and modified from anywhere in the script, including inside functions. To restrict a variable’s visibility to a single function and prevent it from modifying the global one, use the local keyword.
For example, the following script has two variables called status. The global variable has the value of processing, while the local one inside the update_status() function is set to Done:
#!/bin/bash
# Global variable
status="Processing"
update_status() {
# Local variable with the same name
local status="Done"
echo "Inside function: $status"
}
echo "Before function: $status"
update_status
echo "After function: $status"
By default, printing the variable yields processing because it uses the global value. Meanwhile, the function where we set the local variable will output Done.

How do special variables work in Bash?
Bash includes a set of reserved variables that automatically store data regarding the current shell environment. You cannot assign values to them manually as they inherit dynamic data from ongoing and completed processes, including their outputs and states.
These variables generally track script information and arguments:
- $0 – represents the name of the script file currently executing.
- $# – stores the total number of arguments passed to the script.
- $@ – expands to all script arguments, treating each as a separate quoted string.
- $* – expands to all script arguments, treating them as a single concatenated string.
Other variables monitor process control and execution status:
- $$ – displays the Process ID (PID) of the current shell script.
- $! – displays the PID of the last command executed in the background.
- $? – reports the exit status of the last executed command (0 for success, 1-255 for failure).
- $_ – holds the last argument of the previous command.
- $- – shows the current flags and options set for the shell.
For example, this script utilizes special variables to display its own name, process ID, and the success status of a command.
#!/bin/bash echo "Script filename: $0" echo "Current Process ID: $$" # Attempt to list a non-existent file to generate an error ls /dummy_file 2>/dev/null # Print the exit code of the previous command echo "Exit status (0=Success, Non-zero=Fail): $?"
Notice that the variable values are not hard-coded, but instead use a placeholder that changes dynamically based on the shell environment.

How to export and unset Bash variables
Variables defined in a shell are not automatically passed to child processes, such as new scripts or shell sessions initiated from the current one.
If you want to include variables in the current shell for subsequent child processes, use the export command. For example, this script starts a new bash shell session and passes the API_KEY variable to it:
#!/bin/bash # Define and export a variable export API_KEY="12345-ABCDE" # Start a new child shell instance and print the variable bash -c 'echo "Child shell sees: $API_KEY"'
In a real-world scenario, your script might start multiple child processes, and not all of them require the exported variable. For example, you may need to pass passwords or tokens to a specific process, but subsequent operations don’t need them.
To prevent child processes from importing a variable, remove its value from memory by using the unset command:
#!/bin/bash # Define and export a variable export API_KEY="12345-ABCDE" # Start a new child shell instance and print the variable bash -c 'echo "Child shell sees: $API_KEY"' # Remove variable from the memory for subsequent processes unset API_KEY echo "Parent shell after unset: $API_KEY" bash -c 'echo "Child shell sees: $API_KEY"'
In this example, the first child process can retrieve the variable value, but the subsequent processes can’t. Note that the unset affects both the new and the current shell.
How to use quotes and substitution in Bash
Bash provides mechanisms to control how text is interpreted, allowing you to choose between using literal strings or dynamic values.
When to use single vs double quotes
Single quotes (‘example’) enforce literal interpretation of all characters, including $.
For example, the following script prints $HOME instead of its value because we enclose it in single quotes:
#!/bin/bash echo 'The value is $HOME' # Output: The value is $HOME
Double quotes (“example”) allow variables to change their values and pass command standard outputs within the string. For example, the following script passes the value of $HOME instead of printing the literal string:
#!/bin/bash echo "The value is $HOME" # Output: The value is /root

How to use command substitution
Command substitution is used to insert the output of a command directly into variables in your script. To do this, enclose the command within the $( ) syntax like so:
#!/bin/bash backup_file="data_$(date +%F).tar.gz" echo "Backing up to: $backup_file"
This script runs the date +%F command and passes its output as the value for the backup_file variable.

In legacy scripts, you may use backticks (`example`) to enclose your command. However, this is no longer recommended because it complicates nesting.
Common examples of using Bash variables in scripts
Given their flexibility, you can use Bash variables in Bash scripts differently depending on what you want to achieve. You can also combine them with different Bash mechanisms to further enhance your script functionality.
For example, you can combine bash variables with arithmetic operations and if conditionals, like in this example:
#!/bin/bash
count=3
if (( count > 2 )); then
echo "Count is greater than 2"
fi

The variable count holds a number, and the conditional uses its value to decide whether to run the echo command. This demonstrates how variables provide data that Bash can use to make logical decisions.
The if statement in Bash also commonly uses square brackets to specify the conditions that the function will check. For example, this script prints a message if a text file is found within the variable:
#!/bin/bash
file="report.txt"
if [[ $file == *.txt ]]; then
echo "It is a text file"
fi
While variables mustn’t have spaces around them, the condition inside the square brackets of the if statement should. Given their different behaviors, pattern errors commonly occur when combining these bash mechanics together.
Aside from combining it with an if statement, you can also use a variable to store a Bash array, making it easy to loop through its items within a script. Here’s an example:
#!/bin/bash
nums=(1 2 3)
for n in "${nums[@]}"; do
echo "$n"
done
This script sets a variable that contains an array of numbers, iterates through them using the for loop, and passes each item into the echo command.

When working with an array, it’s crucial to enclose your variable in curly braces ({ }) to prevent Bash from reading the variable as nums[@]. It’s also helpful if you want to combine variable values, like in this example:
dirpath="/var/www/site"
backup="${dirpath}_backup"
Without curly braces, Bash would interpret the backup variable as dirpath_backup instead of /var/www/site_backup.
Another common mistake when using variables is not enclosing them with quotes, especially when passing them to functions. The good formatting looks like this:
var="Value of the var" echo "$var"
If the value contains a whitespace, Bash will interpret it as multiple arguments instead of a single string. If you use $var without quotation marks, the echo command will read Value, of, the, and var as individual strings.
How can you build scripts using Bash variables?
Bash variables are the building blocks for creating flexible, automated scripts. By storing values such as filenames, user input, or lists of items, you can create dynamic scripts that help automate complex Linux server administration tasks.
For example, you can use a variable to store a directory path, then loop over all files in that directory and perform an action on each file, like moving, renaming, or backing them up.
Also, you can capture user input in a variable and make decisions based on that input, such as choosing which service to restart or which file to process.
Variables can even hold arrays or lists, letting you handle multiple items efficiently without hardcoding anything.
In addition, you can combine values from multiple variables or attach strings to them, which is helpful when working with dynamic data like process outputs. To learn more, check out our guide on concatenating strings in Bash.

All of the tutorial content on this website is subject to Hostinger's rigorous editorial standards and values.