Skip to content

Latest commit

 

History

History
231 lines (159 loc) · 6.28 KB

variables.md

File metadata and controls

231 lines (159 loc) · 6.28 KB

Variables

Variables are like containers that can be used to store data or information

When we start to write complex logic in bash script there will be some data that are need in more than one place or repeating. We can simply use a variable and use it in all the places where we need them.

Types of Bash Variables

Bash has two types of variables:

1️⃣ System-Defined Variables
2️⃣ User-Defined Variables

System-Defined Variables (Environment Variables)

These are predefined variables provided by the shell and system. You can view all system variables using any of the following command in the terminal:

  • printenv
  • env
  • set

Common System Variables

Variable Description
$HOME User's home directory
$USER Logged-in username
$PATH Directories where the system searches for executables
$SHELL The shell currently in use (/bin/bash, /usr/bin/zsh, etc.)
$PWD Current working directory
$UID User ID
$HOSTNAME Name of the computer
$LANG System language setting

You can use these variables in your bash script. Let's create a bash script and run it.

#!/bin/bash

echo "User Information:"
echo "-----------------"
echo "Username      : $USER"
echo "User ID (UID) : $UID"
echo "Home Dir      : $HOME"
echo ""

echo "System Information:"
echo "-------------------"
echo "Hostname      : $HOSTNAME"
echo "Current Shell : $SHELL"
echo "Current Dir   : $PWD"
echo ""

echo "Environment Settings:"
echo "---------------------"
echo "System Language : $LANG"
echo "Executable Paths: $PATH"

After running this script you will get a some information about your computer.

User-Defined Variables

These are variables created by the user in scripts or the terminal.

Types of User-Defined Variables

Type Description Example
Local Variable Exists only in the current shell/session. my_var="Hello"
Global Variable Can be accessed by child processes. export my_var="Hello"
Read-Only Variable Cannot be modified after assignment. readonly my_var="Hello"
Special Variables Used for script arguments, exit status, etc. $0, $1, $?, $$

Delaring and Accessing a variable

As mentioned above variables hold values. So you need a name for the variable and some value to store in it. You can can declare a variable using a name follwed by and equal sign follwed by the value.

Now, to access this variable you should used $ sign follwed by the variable name.

name="Newton"

echo $name

Data Types

The variables we used above store string type value. There are other data types supported by Bash.

Data Type Description
String Default type; all variables are treated as strings.
Integer Used in arithmetic with $(( )), let, or expr.
Float (Decimal) Not supported natively; use bc or awk for calculations.
Array Indexed lists, e.g., arr=("val1" "val2").
Associative Array Key-value pairs, requires declare -A arr.
Boolean Simulated using 0 (true) and 1 (false).

In bash you dont have to define data type at the time of delaration. Bash Variables Are Untyped In Bash, you can assign any type of value to a variable without specifying a type. Bash automatically interprets variables based on usage.

#!/bin/bash

# STRING (Default type)
name="Newton"
echo "String Example: Hello, $name!"

# INTEGER (Used for arithmetic)
num1=10
num2=5
sum=$((num1 + num2))  # Arithmetic operation
echo "Integer Example: Sum of $num1 and $num2 is $sum"

# FLOAT (Decimals using bc)
num3=5.5
num4=2.2
result=$(echo "$num3 + $num4" | bc)
echo "Float Example: Sum of $num3 and $num4 is $result"

Don't worry about sum and result variable, there will be explained later.

Arrays

Bash supports one-dimensional arrays, which can store multiple values in a single variable.

Declaring an Array

fruits=("Apple" "Banana" "Cherry")

Elements are space-separated inside ().

Accessing Array Elements

echo "First fruit: ${fruits[0]}"
echo "Second fruit: ${fruits[1]}"

Use ${array[index]} to access elements.

Print All Elements

echo "All fruits: ${fruits[@]}"
echo "All fruits: ${fruits[*]}"

Use @ or * to prints all elements.

Get Array Length

echo "Total fruits: ${#fruits[@]}"

${#array[@]} gives array length.

Adding Elements

fruits+=("Mango")
echo "Updated Fruits: ${fruits[@]}"

Replacing an Element

fruits[1]="Grapes"
echo "After Replacement: ${fruits[@]}"

Replaces Banana with Grapes.

Removing an Element

unset fruits[1]  # Removes the second element
echo "After Deletion: ${fruits[@]}"

Use unset to remove an element.

Looping Through an Array

for fruit in "${fruits[@]}"; do
   echo "Fruit: $fruit"
done

Associative Arrays (Key-Value)

Bash 4.0+ supports associative arrays:

declare -A person
person[name]="Newton"
person[age]=125

echo "Name: ${person[name]}"
echo "Age: ${person[age]}"

Use declare -A for key-value pairs.

Full Example

Create a bash script with the following code and run it.

#!/bin/bash

fruits=("Apple" "Banana" "Cherry")

echo "Fruits: ${fruits[@]}"

fruits+=("Mango")

echo "Updated Fruits: ${fruits[@]}"

for fruit in "${fruits[@]}"; do
    echo "Fruit: $fruit"
done