Storing Data With Variables in Bash
13 min read·Jan 1, 2025
In programming, a variable is a named container used to store data referred to as a value.
It can be used to store a wide range of information, such as a filename, a date, a counter, a line of text, and pretty much anything else you can think of.
Depending on certain conditions, this value may change during the execution of the script and be updated either by the developer through instructions, the user through input, or the script itself through logic.
Data types
Bash variables can essentially store 4 different data types: characters, strings, numbers, arrays.
Characters
A character is a unit of text that represents a single symbol or letter.
Characters can be assigned directly without quotes, enclosed in single quotes, or enclosed in double quotes:
char=a
char='b'
char="c"
Strings
A string is a sequence of characters often used to represent words and sentences.
Single word strings can be assigned directly without quotes, enclosed in single quotes, or enclosed in double quotes:
string=Hello
string='Hello'
string="Hello"
Multiple words strings or complex expressions, on the other hand, need to be enclosed in single or double quotes:
hello='Hello World'
path="/home/razvan/scripts/hello.sh"
However, note that strings enclosed in single quotes are treated as literal strings, and their contents are not subject to any form of interpretation or expansion, whereas strings enclosed in double quotes allow for variable substitution, command substitution, and the interpretation of escape sequences.
Numbers
A number is either an integer or a float.
Numbers are assigned directly without quotes, as they would otherwise be considered as strings:
integer=3
float=3.5
Arrays
An array is a special type of variable that contains a collection of data, often of the same type (but not necessarily), organized into a list or sequence.
Arrays are declared using parenthesis () and each element within it is separated by a space character.
# This array contains one element: "Hello"
array=("Hello")
# This array contains four elements: "Hello", "x", "World", 5
array=("Hello" x "World" 5)
Declaring variables
In Bash, to declare a new variable and initialize it with a value, you can use the following syntax:
variable=value
Where:
variableis the name of the variable.valueis the value assigned to that variable.
Note: Unlike in other programming languages, there must be no space character on either side of the equal signal
=.
Capturing the output of commands
To capture the data written by a command to the standard output into a variable, you can use the command substitution expansion $():
variable=$(command)
Using variables
To access and use the value stored in a variable, including environment variables, you can place a dollar sign $ before the name of the variable:
$variable
Example
Let's consider this script:
#!/bin/bash
home_directory=$HOME
echo $home_directory
When executed, it will:
- Define a variable named
home_directoryand initialize it with the value of theHOMEenvironment variable. - Output the value of the
home_directoryvariable using theechocommand.
Which will produce this output:
$ ./script.sh
/Users/razvan
Quoting variables
Just like strings, variables enclosed in single quotes are not expanded and are treated as ordinary characters:
'$variable'
On the other hand, variables enclosed in double quotes are expanded, and their values are substituted into the string:
"$variable"
Note: Variables containing strings with multiple whitespaces and tabs must be enclosed in double quotes for their value to be preserved as is.
Example
Let's consider this script:
#!/bin/bash
files=$(ls)
echo '$files'
echo "$files"
When executed, it will:
- Define a variable named
filesand initialize it with the output of thelscommand. - Output the literal string
'$files'. - Output the value of the
filesvariable.
Which will produce this output:
$ ./script.sh
$files
script.sh
Reassigning variables
To modify the value of an existing variable, you can use the same syntax as for when declaring it:
variable=new_value
Example
Let's consider this script:
#!/bin/bash
echo $USER
USER="learnbackend"
echo $USER
When executed, it will:
- Output the current value of the
USERenvironment variable. - Reassign the value of the
USERvariable to the"learnbackend"string. - Output the current value of the
USERvariable.
Which will produce this output:
$ ./script.sh
razvan
learnbackend
Note: The modification of environment variables within a script is limited to the script itself and doesn't propagate to the environment of the shell the script was launched from.
To update the value of an environment variable from a script, you must use a combination of the
exportandsourcecommands, as seen in the lesson called The Shell Environment.
Read-only variables
Read-only variables are variables whose value cannot be changed during the execution of the script.
They are generally used to store configuration constants or values that should remain fixed, such as file paths, API keys, thresholds, and so on.
To declare a read-only variable, you can prepend the readonly keyword to your variable:
readonly variable=value
Note: Any attempt to modify a read-only variable will result in a
readonly variableerror.
Example
Let's consider this script:
#!/bin/bash
readonly API_KEY="ABCDEF"
API_KEY="123456"
echo $API_KEY
When executed, it will:
- Define a read-only variable named
API_KEYand initialize it with the"ABCDEF"string. - Try to reassign the value of the
API_KEYvariable to the"123456"string. - Output the value of the
API_KEYvariable.
Which will produce this output:
$ ./script.sh
./script.sh: line 5: API_KEY: readonly variable
ABCDEF
Positional arguments
Positional arguments, also known as command-line arguments, are values provided to a Bash script when run from the command line.
They are used to pass dynamic information to the script to modify its behavior, such as flags:
$ command [argument ...]
These arguments can be accessed in a Bash script through the following special variables:
$0: This variable holds the name of the script itself.$1,$2, ...: These variables hold the individual positional arguments passed to the script, where$1represents the first argument,$2represents the second argument, and so on.$#: This variable holds the total number of positional arguments passed to the script.$@: This variable represents all the positional arguments as a list. It treats each argument as a separate word and preserves any spaces or special characters.$*: This variable also represents all positional arguments but treats them as a single string, not as individual words.
Example
Let's consider this script:
#!/bin/bash
echo "Executing the script: $0"
echo "There are $# arguments"
echo "The arguments are: $*"
When executed, it will:
- Output the name of the script stored in the
$0variable. - Output the number of arguments passed to the script stored in the
$#variable. - Output the list of arguments passed to the script in the form of a string of characters stored in the
$*variable.
Which will produce this output:
$ ./script.sh hello world
Executing the script: ./script.sh
There are 2 arguments
The arguments are: hello world
Variable naming convention
In programming, a naming convention is a set of rules for choosing the character sequence to be used for identifiers such as variables, functions, and so on.
In Bash, variable names are case-sensitive, and by convention, are written in snake case.
They should:
- Start with a letter or an underscore character
_. - Only contain letters, numbers, and underscores.
- Not contain spaces or special characters.
- Use descriptive names that reflect their purpose.
- Not include reserved keywords, such as
if,then,else,fi, and so on. - Be written in uppercase if their value is not meant to change (i.e. constants).
Example
Let's consider the following variables:
# Number
age=33
# Single character
_separator=x
# String of characters
first_name=John
# String of characters with multiple words
full_name="John Doe"
# Constant
readonly MAX_RETRIES=5
Summary
Here's a summary of what you've learned in this lesson:
- A variable is a named container used to store data referred to as a value.
- A variable can contain four data types: characters, strings, numbers, and arrays.
- The
variable=valuesyntax is used to declare a new variable and assign it a value. - The
variable=(value)syntax is used to declare a new array. - The
variable=$(command)syntax is used to store the output of a command into a variable. - The
$variablesyntax is used to access a variable's value. - The
variable=new_valuesyntax is used to reassign the value of an existing variable. - The
readonlykeyword is used to define immutable variables.
Enjoying the courses?
I've made these courses completely free so anyone can learn from them. If they've helped you and you'd like to actively support the work behind BackendBrewery, you can leave a tip:
Support BackendBrewery