---
description: This pages contains few worked-out examples for you to practice!
---

# Worked-out Examples

1. **Read a 5 digit number and print it in reverse. Check if the input is 5 digit positive number**

```bash
#!/bin/bash

# Function to reverse a number
reverse_number() {
    local num=$1
    local reversed=0
    while [ $num -ne 0 ]; do
        reversed=$((reversed * 10 + num % 10))
        num=$((num / 10))
    done
    echo "$reversed"
}

# Read input
read -p "Enter a 5-digit positive number: " input_num

# Validate input
if [[ $input_num =~ ^[0-9]{5}$ ]]; then
    # Convert to integer
    input_num=$((input_num))

    # Reverse the number
    reversed=$(reverse_number "$input_num")

    # Print result
    echo "The reversed number is: $reversed"
else
    echo "Invalid input. Please enter a 5-digit positive number."
fi

```

2. **Read two input values, equate them to two variables and perform the swap**

```bash
#!/bin/bash

# Prompt user for two numbers
echo "Enter the first number:"
read num1
echo "Enter the second number:"
read num2

# Print original values
echo "Before swap:"
echo "num1 = $num1"
echo "num2 = $num2"

# Swap using arithmetic operations
num1=$((num1 + num2))
num2=$((num1 - num2))
num1=$((num1 - num2))

# Print swapped values
echo -e "\nAfter swap:"
echo "num1 = $num1"
echo "num2 = $num2"
```



3. **Read a non-zero input number and check if it is a palindrome**

```bash
#!/bin/bash

# Read input number
echo "Enter a number:"
read num

# Check if the number is negative
if [ "$num" -lt 0 ]; then
    echo "Negative numbers cannot be palindromes."
    exit 1
fi

# Convert to positive number
num=$((num < 0 ? -num : num))

# Store original number
original=$num

# Reverse the number
reverse=""
while [ $num -ne 0 ]; do
    remainder=$((num % 10))
    reverse="$remainder$reverse"
    num=$((num / 10))
done

# Check if palindrome
if [ "$original" = "$reverse" ]; then
    echo "The number $original is a palindrome."
else
    echo "The number $original is not a palindrome."
fi

```

4. **Reverse an input number with out using a Loop**

```bash
#!/bin/bash

number=12345
reversed=$(printf "%s" "$number" | rev)
echo "Original: $number"
echo "Reversed: $reversed"
```

5. **Read a 10 digit number as input, identify even digits, odd digits and digits that are prime numbers by splitting the input number**

```bash
#!/bin/bash

# Function to check if a number is prime
is_prime() {
    local num=$1
    if (( num <= 1 )); then
        return 1
    fi
    for (( i=2; i*i<=num; i++ )); do
        if (( num % i == 0 )); then
            return 1
        fi
    done
    return 0
}

# Read input number
echo "Enter a 10-digit number:"
read number

# Ensure the number is 10 digits long
if [[ ${#number} -ne 10 ]]; then
    echo "Error: Number should be exactly 10 digits long."
    exit 1
fi

# Initialize counters for even, odd, and prime digits
even_count=0
odd_count=0
prime_count=0

# Convert number to string for easy iteration
num_str=$number

# Check each digit
for (( i=0; i<${#num_str}; i++ )); do
    digit=${num_str:$i:1}
    
    # Check if it's even or odd
    if (( digit % 2 == 0 )); then
        (( even_count++ ))
    else
        (( odd_count++ ))
    fi
    
    # Check if it's prime (only for single-digit numbers)
    if [[ $digit -ge 2 && $digit -le 9 ]]; then
        if is_prime $digit; then
            (( prime_count++ ))
        fi
    fi
done

# Display results
echo "Even digits: $even_count"
echo "Odd digits: $odd_count"
echo "Prime digits: $prime_count"

if [ "$num_str" = "$digit" ]; then
    echo "The number $number is also prime."
else
    echo "The number $number is not prime."
fi

```

6. **Read .txt files from the working directory and print the file names in alphabetic order**

```bash
#!/bin/bash

# List all .txt files and sort them alphabetically
for file in *.txt; do
    echo "$file"
done | sort
```

```bash
#!/bin/bash

# List all .txt files (including hidden ones) and sort them alphabetically
for file in .*/*.txt; do
    echo "$file"
done | sort -d
```

7. **Read the .txt files from the working directly and print the file names by modification date**

```bash
#!/bin/bash

# Find .txt files (including hidden ones) and sort by modification date
find . -maxdepth 1 -name "*.txt" -type f -printf "%T+ %p\n" | sort

# Explanation of the find command:
#   . - start searching from current directory
#   -maxdepth 1 - don't go into subdirectories
#   -name "*.txt" - look for files ending with .txt
#   -type f - only find regular files
#   -printf "%T+ %p\n" - print the modification time followed by the filename

```

8. **Read the .txt files from the input directory and print the file names by modification date**

```bash
#!/bin/bash

# Specify the directory to search in
search_dir="/path/to/directory"

# Find .txt files in the specified directory and sort by modification date
find "$search_dir" -maxdepth 1 -name "*.txt" -type f -printf "%T+ %p\n" | sort

# Explanation of the find command:
#   "$search_dir" - start searching from the specified directory
#   -maxdepth 1 - don't go into subdirectories
#   -name "*.txt" - look for files ending with .txt
#   -type f - only find regular files
#   -printf "%T+ %p\n" - print the modification time followed by the filename

```

9. **A calculator program with two non negative intergers as input**

```bash
#!/bin/bash

# Function to clear the screen
clear_screen() {
    tput reset
}

# Main menu
while true; do
    clear_screen
    echo "Simple Bash Calculator"
    echo "------------------------"
    echo "1. Addition"
    echo "2. Subtraction"
    echo "3. Multiplication"
    echo "4. Division"
    echo "5. Exit"
    echo -e "\nEnter your choice (1-5): "
    
    read choice

    case $choice in
        1)
            echo -e "\nEnter two non-negative integers:"
            read num1 num2
            if [ $num2 -eq 0 ] && [ $choice -eq 4 ]; then
                echo "Cannot divide by zero!"
            else
                result=$((num1 + num2))
                echo "Result: $result"
            fi
            ;;
        2)
            echo -e "\nEnter two non-negative integers:"
            read num1 num2
            result=$((num1 - num2))
            echo "Result: $result"
            ;;
        3)
            echo -e "\nEnter two non-negative integers:"
            read num1 num2
            result=$((num1 * num2))
            echo "Result: $result"
            ;;
        4)
            echo -e "\nEnter two non-negative integers:"
            read num1 num2
            if [ $num2 -eq 0 ] && [ $choice -eq 4 ]; then
                echo "Cannot divide by zero!"
            else
                result=$((num1 / num2))
                echo "Result: $result"
            fi
            ;;
        5)
            echo "Exiting..."
            break
            ;;
        *)
            echo "Invalid choice. Please try again."
            sleep 1
            ;;
    esac
    echo -e "\nPress Enter to continue..."
    read
done

```

10. **Provide a square root and cube root of a number**

```bash
#!/bin/bash

# Function to calculate square root
square_root() {
    local num=$1
    if (( num < 0 )); then
        echo "Error: Square root is not defined for negative numbers."
        return 1
    fi
    echo "scale=2; sqrt($num)" | bc
}

# Function to calculate cube root
cube_root() {
    local num=$1
    if (( num < 0 )); then
        echo "Error: Cube root is not defined for negative numbers."
        return 1
    fi
    echo "scale=2; cbrt($num)" | bc
}

# Main program
echo "Enter a non-negative integer:"
read number

square_result=$(square_root $number)
cube_result=$(cube_root $number)

echo "Square root of $number = $square_result"
echo "Cube root of $number = $cube_result"

```

11. **Read a 10 digit number as input, reverse it and check if each digit is divisible by 2**

```bash
#!/bin/bash

# Function to reverse a number
reverse_number() {
    local num=$1
    local reversed=0
    while [ $num -ne 0 ]; do
        digit=$((num % 10))
        reversed=$((reversed * 10 + digit))
        num=$((num / 10))
    done
    echo $reversed
}

# Function to check if a number is divisible by 2
is_divisible_by_2() {
    local num=$1
    if [ $(($num % 2)) -eq 0 ]; then
        echo "true"
    else
        echo "false"
    fi
}

# Main program
echo "Enter a 10-digit non-negative integer:"
read number

if [[ ${#number} -ne 10 ]]; then
    echo "Error: Number should be exactly 10 digits long."
    exit 1
fi

if ! [[ $number =~ ^[0-9]+$ ]]; then
    echo "Error: Number should only contain digits."
    exit 1
fi

reversed=$(reverse_number $number)
echo "Original number: $number"
echo "Reversed number: $(reverse_number $number)"

for digit in $(echo $reversed | sed 's/./& /g'); do
    result=$(is_divisible_by_2 $digit)
    echo "Is $digit divisible by 2? $result"
done

```

12. **Read a paragraph as input and identify number of vowels are present in the paragraph**

```bash
#!/bin/bash

# Read input from user
echo "Please enter a paragraph:"
read paragraph

# Initialize vowel counter
vowel_count=0

# Convert to lowercase and remove non-alphabetic characters
cleaned_paragraph=$(echo "$paragraph" | tr '[:upper:]' '[:lower:]' | tr -cd '[:alpha:]')

# Count vowels
for (( i=0; i<${#cleaned_paragraph}; i++ )); do
    char=${cleaned_paragraph:$i:1}
    if [[ $char == [aeiou] ]]; then
        ((vowel_count++))
    fi
done

# Print result
echo "The paragraph contains $vowel_count vowels."

```

13. **Read the paragraph as input and identify number of consonants are present in the paragraph**

```bash
#!/bin/bash

# Read input from user
echo "Please enter a paragraph:"
read paragraph

# Initialize consonant counter
consonant_count=0

# Convert to lowercase and remove non-alphabetic characters
cleaned_paragraph=$(echo "$paragraph" | tr '[:upper:]' '[:lower:]' | tr -cd '[:alpha:]')

# Count consonants
for (( i=0; i<${#cleaned_paragraph}; i++ )); do
    char=${cleaned_paragraph:$i:1}
    if [[ $char != [aeiou] ]]; then
        ((consonant_count++))
    fi
done

# Print result
echo "The paragraph contains $consonant_count consonants."

```

14. **Convert the current date-time into EST, PST, MST, CST Timezone**

```bash
#!/bin/bash

# Function to display current time in given timezone
display_time() {
    echo "$1: $(TZ=$2 date '+%Y-%m-%d %H:%M:%S')"
}

# Current time in UTC
echo "Current time (UTC): $(date)"

# Convert to EST
display_time "EST" "America/New_York"

# Convert to PST 
display_time "PST" "America/Los_Angeles"

# Convert to MST
display_time "MST" "America/Denver"

# Convert to CST
display_time "CST" "America/Chicago"

```

15. **Calculate the Age of a person in years, month, days when his/her birth date is provided as input**

```bash
#!/bin/bash

# Function to calculate age
calculate_age() {
    local birth_date="$1"
    
    # Parse birth date
    local birth_year=$(date -d "$birth_date" +%Y)
    local birth_month=$(date -d "$birth_date" +%m)
    local birth_day=$(date -d "$birth_date" +%d)
    
    # Get current date
    local current_date=$(date +%Y-%m-%d)
    
    # Calculate age in years, months, days
    local age_years=$(( $(date -d "$current_date" +%Y) - $birth_year ))
    local age_months=$(( (10#$birth_month + 12*10#$birth_day/31) - (10#$(date -d "$current_date" +%m) + 12*10#$(date -d "$current_date" +%d)/31) ))
    local age_days=$(( $(date -d "$current_date" +%j) - $(date -d "$birth_date" +%j) ))

    echo "Age: $age_years years, $age_months months, $age_days days"
}

# Read birth date from user
echo "Enter your birth date (YYYY-MM-DD): "
read birth_date

# Calculate and display age
calculate_age "$birth_date"

```

16. **Provide a date as input and return the "day" of date in a respective week along with the week number in that given year.**

```bash
#!/bin/bash

# Function to get day of week and week number
get_day_and_week() {
    local input_date="$1"
    
    # Parse input date
    local year=$(date -d "$input_date" +%Y)
    local month=$(date -d "$input_date" +%m)
    local day=$(date -d "$input_date" +%d)
    
    # Get day of week (1-7, Monday-Sunday)
    local day_of_week=$(date -d "$year-$month-$day" +%w)
    
    # Get week number (1-53, ISO standard)
    local week_number=$(date -d "$year-$month-$day" +%V)
    
    # Map day of week numbers to names
    local day_names=(Sunday Monday Tuesday Wednesday Thursday Friday Saturday)
    local day_name="${day_names[$((day_of_week-1))]}"
    
    echo "Day: $day_name"
    echo "Week Number: $week_number"
}

# Read input date from user
echo "Enter a date (YYYY-MM-DD): "
read input_date

# Call function to get and display results
get_day_and_week "$input_date"

```
