Bash Variable
Bash Variable in bash shell scripting is a named reference that stores a value for later use in a script or terminal session. A bash variable can hold text, numbers, command output, paths, arrays, and other string-based values used by commands.
Variables make bash scripts easier to read and maintain. Instead of repeating the same value many times, you can assign it once and reuse it with variable expansion such as $name or ${name}.
Important bash variable rules before writing scripts
- Bash variables are not declared with fixed data types. A variable value is treated mainly as text, even when it looks like a number.
- A variable is created automatically when a value is assigned to a valid variable name.
- Do not put spaces before or after
=during assignment. Usename=value, notname = value. - Variable names usually contain letters, numbers, and underscores, and should not start with a number.
- Use quotes around variable expansions when the value may contain spaces, tabs, or special characters.
We shall go through the following topics in this tutorial.
- Bash variable assignment syntax
- Bash variable examples for numbers, strings, and arrays
- Bash variable expansion with braces and quotes
- Bash command substitution stored in a variable
- Bash local variable inside a function
- Bash environment variable export
- Bash variable FAQ and editorial QA checklist
Bash variable assignment syntax
Following is the syntax to initialize a variable.
variableReference=value
Note : No space should be given before and after = , failing which produces error “syntax error near unexpected token“.
The left side is the variable name, and the right side is the value. To read the value later, prefix the variable name with $.
name="Alice"
echo "$name"
Use braces when the variable name is followed immediately by more characters. This makes the boundary of the variable name clear.
file="report"
echo "${file}.txt"
echo "${file}_backup.txt"
Bash variable examples for number, character, string, and array values
Following example demonstrates simple initialization of bash variables of types : number, character, string and array.
Bash Script File
#!/bin/bash
# number variable
num=10
echo $num
# character variable
ch='c'
echo $ch
# string variable
str="Hello Bob!"
echo $str
# array variable
arr=( "bash" "shell" "script" )
echo "${arr[0]}"
echo "${arr[1]}"
echo "${arr[2]}"
When the above bash variable example is run in Terminal, we will get the following output.
Output
$ ./bash-variable-example
10
c
Hello Bob!
bash
shell
script
In the array example, indexes start from 0. Therefore, ${arr[0]} prints the first array element, ${arr[1]} prints the second element, and ${arr[2]} prints the third element.
Bash variable names and assignment mistakes to avoid
A bash variable name should be easy to understand and valid for shell parsing. Names such as file_name, count, and backup_dir are safe choices.
backup_dir="/home/user/backups"
count=5
file_name="notes.txt"
The following assignments are common mistakes. The first one has spaces around =, and the second one starts the variable name with a number.
name = "Alice"
1name="Alice"
Use meaningful names in real scripts. For example, source_dir is clearer than x when the variable stores a directory path.
Bash variable expansion with quotes
In bash scripting, quoting variable expansions is important when a value contains spaces or special characters. Prefer "$variable" for ordinary string values.
message="Hello Bash User"
echo "$message"
If you use echo $message without quotes, the script may still appear to work for simple text. However, quoted expansion is safer in commands that process file names, paths, or user input.
file_name="my notes.txt"
cat "$file_name"
Single quotes and double quotes behave differently. Single quotes preserve the text exactly, while double quotes allow variable expansion.
name="Bob"
echo 'Hello $name'
echo "Hello $name"
Hello $name
Hello Bob
Bash variable from command output
You can store the output of a command in a bash variable using command substitution. The modern and readable form is $(command).
today=$(date +%F)
echo "Today is $today"
This is useful when a script needs to build file names, log entries, backup folders, or conditional messages based on command results.
backup_file="backup-$(date +%F).tar.gz"
echo "$backup_file"
Bash readonly variable for values that should not change
Use readonly when a variable value should not be changed later in the same shell process. This is useful for constants such as script paths, fixed labels, and configuration values.
readonly APP_NAME="Report Generator"
echo "$APP_NAME"
After a variable is marked readonly, assigning a new value to it causes an error.
readonly site="TutorialKart"
site="Example"
bash: site: readonly variable
Bash Local Variable
Bash Local Variable is used to override a global bash variable, in local scope, if already present with the same name.
In bash, local is used inside a function. The variable exists mainly inside that function call and does not permanently replace the variable with the same name outside the function.
Bash local variable syntax inside a function
Following is the syntax of a bash local variable.
local variableReference=value
The local keyword should be used inside a function body. It is commonly used to avoid accidental changes to global variables.
Bash local variable example with global and function scope
Following is an example bash script to demonstrate the usage of local variable.
Bash Script File
#!/bin/bash
# bash variable
SHELL="Unix"
function bashShell {
# bash local variable
local SHELL="Bash"
echo $SHELL
}
echo $SHELL
bashShell
echo $SHELL
When above bash local variable example is run in Terminal, we will get the following output.
Output
arjun@arjun-VPCEH26EN:~/workspace/bash$ ./bash-local-variable-example
Unix
Bash
Unix
The first echo statement is in global scope and SHELL has value of UNIX, but when bashShell function is called, the local variable SHELL overrides the global variable and hence the echo $SHELL echoed Bash.
After the function call finishes, the outer SHELL variable still has the value Unix. This is why the third line of output is Unix.
Bash environment variable export
A normal shell variable is available in the current shell. To make a variable available to child processes started from that shell, use export.
APP_ENV="development"
export APP_ENV
bash -c 'echo "$APP_ENV"'
You can also assign and export in one line.
export APP_ENV="development"
Use exported variables for settings that another script or command must read. Do not export every variable by default; local script-only values can remain ordinary shell variables.
Bash unset command to remove a variable
Use unset to remove a bash variable from the current shell.
city="Hyderabad"
echo "$city"
unset city
echo "$city"
After unset city, the variable no longer has a value in the current shell session.
Bash variable examples used in real scripts
The following short script uses variables for a source file, destination directory, and generated backup name.
#!/bin/bash
source_file="notes.txt"
backup_dir="backups"
backup_file="${backup_dir}/notes-$(date +%F).txt"
mkdir -p "$backup_dir"
cp "$source_file" "$backup_file"
echo "Backup created: $backup_file"
This example shows three common bash variable practices: quote file paths, use braces when combining variable names with other text, and use command substitution when a value must be generated dynamically.
Common bash variable errors and fixes
| Error or symptom | Likely reason | Fix |
|---|---|---|
syntax error near unexpected token | Spaces around = during assignment | Write name=value |
| Variable prints as empty | Variable name is misspelled or unset | Check the exact name and use echo "$name" |
| File command fails for names with spaces | Variable expansion is not quoted | Use "$file_name" |
| Text after variable name is treated as part of the name | Braces are missing | Use ${name}_suffix |
| Function changes a variable unexpectedly | Global variable is modified inside a function | Use local for function-only values |
Bash variable FAQ
Do bash variables have data types?
Bash variables do not have fixed data types like many programming languages. Values are mostly stored as strings. Arithmetic operations can treat suitable values as numbers when used in arithmetic contexts.
Why should there be no spaces around = in a bash variable assignment?
In bash, name=value is parsed as an assignment. If you write name = value, bash treats name as a command and = and value as arguments, which causes an error or unexpected behavior.
When should I use ${variable} instead of $variable in bash?
Use ${variable} when the variable is next to other characters, such as ${file}_backup. Braces make the variable name clear and prevent bash from reading the suffix as part of the variable name.
What is the difference between a local variable and an exported variable in bash?
A local variable is limited to a function scope when declared with local. An exported variable is placed in the environment so that child processes started from the shell can read it.
How do I store command output in a bash variable?
Use command substitution with $(command). For example, today=$(date +%F) stores the formatted date output in the variable named today.
Bash variable tutorial QA checklist
- Confirm every assignment example uses
name=valuewithout spaces around=. - Check that file path examples quote variable expansions such as
"$file_name". - Use
${variable}when a variable is joined with suffixes or extensions. - Keep
localexamples inside bash functions only. - Use output code blocks only for terminal results, not for executable bash commands.
Bash variable tutorial summary
In this Bash Tutorial – Bash Variable, we have learnt that there are no data types in bash, and the syntax to initialize a variable, and also about local bash local variables with example scripts.
We also covered variable expansion, quotes, arrays, command substitution, readonly variables, exported environment variables, and common mistakes that occur while writing bash variable assignments.
TutorialKart.com