Variables allow us to store values that we can reuse throughout our Bash scripts. They are an essential part of any programming language. This article will cover how to define, use and export variables in Bash.
Bash Variables
Variables allow us to store values that we can reuse throughout our Bash scripts. They are an essential part of Bash programming.
Defining Variables
We define variables using the format:
VARNAME=value
For example:
NAME="John"
AGE=30
HEIGHT=5.11
We define string, integer and float variables.
Variable names must start with a letter or underscore, and can contain numbers. String values should be quoted.
We can define multiple variables in one line:
NAME="John" AGE=30 HEIGHT=5.11
Using Variables
We access a variable's value using $VARNAME
:
echo $NAME #John
We can perform operations on variables:
AGE=$((AGE + 1)) #31
HEIGHT=$((HEIGHT * 2.54)) #12.95 cm
We can concatenate variables and strings:
FULLNAME="$NAME Smith"
echo $FULLNAME #John Smith
Exporting Variables
Variables defined in a script are local. We can export them to make them available to child processes using export
:
export NAME
We can then access the exported variable from a subshell:
(
echo $NAME
echo $FULLNAME
)
#John
#John Smith
String Interpolation
You can mention variables in double quotes to concatenate with other values.
export NAME
FULLNAME="$NAME Smith"
echo "My name is $FULLNAME and I am $AGE years old."
#My name is John Smith and I am 31 years old.
Here we define variables, perform operations, export one and concatenate variables to demonstrate the full process.
Summary:
Bash variables allow us to store and reuse data in our scripts. They start with a letter or underscore and then can contain letters, numbers and underscores.
The main points about Bash variables are:
Definition: Variables are defined using
VARNAME=value
. String values should be quoted.Access: We access a variable's value using
$VARNAME
.Operations: We can perform basic math operations on integer variables using
$((...))
.Concatenation: We can concatenate variables and strings using the
"
operator.Exporting: We can export variables using
export
to make them available to child processes.No Type: Bash variables do not have a fixed type like in other languages. Any variable can store a string, integer or float value.
Reassigning: We can reassign new values to variables at any time.
Naming: Variable names are case-sensitive.
Bash variables provide a basic but useful way to store and reuse data within our scripts. The main limitation is the lack of types, but this flexibility also makes Bash variables easy to work with.
Disclaim: This article was generated with AI (Rix).