What Is a Variable in Bash Scripting?


Angela Bailey

A variable in Bash scripting is a placeholder for storing data. It is a way to assign a name to a value, which can then be referenced and manipulated throughout the script. Variables are crucial for dynamic and interactive scripting, allowing scripts to adapt and respond to different inputs.

Declaring Variables

In Bash, variables are declared by assigning a value to them using the = operator. The variable name must start with a letter or underscore, followed by any combination of letters, numbers, or underscores.


name="John Doe"

In the above example, we have declared two variables: name and age. The name variable stores the value “John Doe”, while the age variable stores the value 25.

Accessing Variables

To access the value stored in a variable, we use the dollar sign ($) followed by the variable name.


echo "Name: $name"
echo "Age: $age"

The above code will output:

Name: John Doe
Age: 25

Using Variables in Commands

Bash allows us to use variables within commands by enclosing them in curly braces ({}). This is useful when we want to concatenate variables with other strings or pass them as arguments to commands.


echo "${greeting}, $name"

The above code will output:

Hello, John Doe

Modifying Variables

We can modify the value of a variable by assigning a new value to it. Bash also provides various operators for performing arithmetic and string manipulation on variables.

Arithmetic Operations

Bash supports arithmetic operations on variables using the $(( )) syntax. The result of the operation is assigned to the variable.



sum=$((num1 + num2))
echo "Sum: $sum"

product=$((num1 * num2))
echo "Product: $product"

The above code will output:

Sum: 15
Product: 50

String Manipulation

Bash provides several operators for manipulating strings stored in variables.

  • Concatenation (+): Concatenates two strings together.
  • Length (#): Returns the length of the string.
  • Substring ( : ): Extracts a portion of the string.



concatenated="${str1} ${str2}"
echo "Concatenated: $concatenated"

echo "Length of str1: $length"

echo "Substring of str2: $substring"

The above code will output:

Concatenated: Hello World
Length of str1: 5
Substring of str2: Wor


Variables are essential in Bash scripting for storing and manipulating data. They allow scripts to be dynamic and interactive, adapting to different inputs and scenarios. By understanding how to declare, access, and modify variables, you can harness the power of Bash scripting to create powerful and flexible scripts.

Discord Server - Web Server - Private Server - DNS Server - Object-Oriented Programming - Scripting - Data Types - Data Structures

Privacy Policy