Logo

Bash Scripting Guide: Variables and Data Types

In Bash scripting, variables are used to store and manipulate data. Understanding data types and proper variable usage is fundamental to writing effective scripts.

Table of Contents

  1. Variables
    1. Declaring Variables
    2. Accessing Variables
  2. Data Types
    1. Strings
    2. Integers
    3. Arrays
  3. Special Variables
  4. Examples
    1. Basic Variable Usage
    2. Arithmetic Operations
    3. Array Example

1 Variables

1.1 Declaring Variables

Variables in Bash are created without explicit data types. Follow these conventions:


# Variable declaration and assignment
variable_name="value"

1.2 Accessing Variables

To access the value of a variable, prefix it with a $ symbol:


echo $variable_name

2 Data Types

Bash primarily supports three data types: strings, integers, and arrays.

2.1 Strings

Strings are sequences of characters. Use single or double quotes for string assignment:


name='John'
greeting="Hello, $name!"

2.2 Integers

Bash treats all variables as strings by default. To perform arithmetic operations, use the (( )) construct:


num1=5
num2=3

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

2.3 Arrays

Arrays store multiple values under a single variable. Declare an array using parentheses:


fruits=("Apple" "Banana" "Orange")

# Accessing array elements
echo "First fruit: ${fruits[0]}"

3 Special Variables

Bash provides special variables for various purposes:

4 Examples

4.1 Basic Variable Usage


# Basic variable usage
name="Alice"
echo "Hello, $name!"

4.2 Arithmetic Operations


# Arithmetic operations
num1=8
num2=4

result=$((num1 / num2))
echo "Result: $result"

4.3 Array Example


# Array example
colors=("Red" "Green" "Blue")

# Loop through array elements
for color in "${colors[@]}"; do
    echo "Color: $color"
done


Continue to Part 4: Control Structures.

Go back to Bash Scripting Guide.

Visit other Developer Guides.