Essential Bash Scripting Examples for Linux Users

1. Prime Numbers

This program finds the prime numbers between two input numbers (M < N).

#!/bin/bash

echo "Program to find the prime numbers between two input numbers (M < N)"
echo

echo "Enter the value of M:"
read M

echo "Enter the value of N:"
read N

# Validate input
if [ $M -lt 2 ]
then
    M=2
fi

echo "Prime numbers between $M and $N are:"

for ((num=M; num<=N; num++))
do
    is_prime=1

    for ((i=2; i*i<=num; i++))
    do
        if (( num % i == 0 ))
        then
            is_prime=0
            break
        fi
    done

    if (( is_prime == 1 ))
    then
        echo $num
    fi
done

2. Palindrome Check

This program determines whether a given number is a palindrome.

#!/bin/bash

echo "Program to find whether a given number is a palindrome or not."
echo

echo "Enter a number:"
read number

# Initialize variables
reverse=0
original=$number

while [ $number -ne 0 ]
do
    remainder=$((number % 10))
    reverse=$((reverse * 10 + remainder))
    number=$((number / 10))
done

if [ $original -eq $reverse ]
then
    echo "$original is a palindrome."
else
    echo "$original is not a palindrome."
fi

3. Sum of Digits

(i) Using Loops

#!/bin/bash

echo "Program to find the sum of digits (using loops)."
echo

echo "Enter a number:"
read number

sum=0

while [ $number -gt 0 ]
do
    digit=$((number % 10))
    sum=$((sum + digit))
    number=$((number / 10))
done

echo "Sum of digits (using loops) is: $sum"

(ii) Without Using Loops

#!/bin/bash

echo "Program to find the sum of digits (without using loops)."
echo

echo "Enter a number:"
read number

sum=$(echo "$number" | sed 's/./& /g' | awk '{ for (i=1; i<=NF; i++) s += $i } END { print s }')

echo "Sum of digits (without using loops) is: $sum"

5. Read, Write, and Execute Permissions

This script checks and displays all files in the current directory that have full read, write, and execute permissions.

#!/bin/bash

echo "Program to check and display all files which have read, write, and execute permissions."
echo

echo "Files with read, write, and execute permissions:"

for file in *
do
    if [ -f "$file" ] && [ -r "$file" ] && [ -w "$file" ] && [ -x "$file" ]
    then
        echo "$file"
    fi
done

6. Copy File Within the Same Directory

#!/bin/bash

echo "Program to copy a file in the current directory."
echo

echo "Enter the name of the file to copy:"
read source_file

# Check whether the source file exists
if [ ! -f "$source_file" ]
then
    echo "File '$source_file' does not exist."
    exit 1
fi

echo "Enter the name for the new copy:"
read destination_file

cp "$source_file" "$destination_file"

if [ $? -eq 0 ]
then
    echo "File '$source_file' has been copied to '$destination_file'."
else
    echo "Failed to copy '$source_file'."
fi

7. Copy File Between Two Directories

#!/bin/bash

echo "Program to copy a file to a different directory."
echo

echo "Enter the path of the file to copy:"
read source_file

# Check if the source file exists
if [ ! -f "$source_file" ]
then
    echo "Error: File '$source_file' does not exist."
    exit 1
fi

echo "Enter the destination directory:"
read destination_dir

# Check if the destination directory exists
if [ ! -d "$destination_dir" ]
then
    echo "Error: Directory '$destination_dir' does not exist."
    exit 1
fi

cp "$source_file" "$destination_dir"

if [ $? -eq 0 ]
then
    echo "File '$source_file' has been copied to '$destination_dir'."
else
    echo "Failed to copy '$source_file'."
fi

8. Creating and Comparing Two Files

This script creates two text files and uses the comm command to find unique and common entries.

#!/bin/bash

echo "Program to compare two input text files and display unique and common entries."
echo

echo "Creating data files..."

cat << EOF > file1.txt
apple
banana
cherry
date
fig
grape
EOF

cat << EOF > file2.txt
banana
cherry
date
kiwi
lemon
mango
EOF

echo "Data files created: file1.txt and file2.txt"

sort file1.txt -o file1.txt
sort file2.txt -o file2.txt

echo "Comparing files for unique and common entries..."
comm file1.txt file2.txt

9. Count Vowels in a String

#!/bin/bash

echo "Program to display the number of vowels in an input string."
echo

read -p "Enter a string: " input_string

vowel_count=0

for ((i=0; i<${#input_string}; i++))
do
    char="${input_string:i:1}"
    if [[ "$char" =~ [aeiouAEIOU] ]]
    then
        ((vowel_count++))
    fi
done

echo "Number of vowels in the string: $vowel_count"

10. Convert Uppercase to Lowercase

This script toggles the case of an input string using the tr command.

#!/bin/bash

echo "Program to convert an input string from uppercase to lowercase and vice versa."
echo

read -p "Enter a string: " input_string

converted_string=$(echo "$input_string" | tr '[:upper:][:lower:]' '[:lower:][:upper:]')

echo "Original string : $input_string"
echo "Converted string: $converted_string"

11. Search for a Word Pattern in a File

#!/bin/bash

read -p "Enter a word to search for: " search_word
read -p "Enter the filename to search in: " filename

# Check if the file exists
if [ ! -f "$filename" ]
then
    echo "Error: File '$filename' does not exist."
    exit 1
fi

echo "Searching for '$search_word' in '$filename'..."

grep -n "$search_word" "$filename"

if [ $? -eq 0 ]
then
    echo "Search completed."
else
    echo "No matches found for '$search_word'."
fi

12. Factorial Calculation

(i) Using a For Loop

#!/bin/bash

read -p "Enter a number: " num

fact=1
for ((i=1; i<=num; i++))
do
    fact=$((fact * i))
done

echo "Factorial of $num is: $fact"

(ii) Using a While Loop

#!/bin/bash

read -p "Enter a number: " num

fact=1
while [ $num -gt 1 ]
do
    fact=$((fact * num))
    num=$((num - 1))
done

echo "Factorial is: $fact"