w3resource

Bash Script Modularization: Exercises, Solutions & Explanation

1.

Greeting Function:

Write a Bash script that defines a function called greet which takes a name as an argument and prints a greeting message using that name.

Code:

#!/bin/bash

# Define the greet function
greet() {
    local name=$1
    echo "Hello, $name! Welcome!"
}

# Call the greet function with a name
greet "Kalevi"

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh
Hello, Kalevi! Welcome!

Explanation:

In the exercise above,

  • Define a function called "greet()" using the greet() { ... } syntax.
  • Inside the function:
    • Declare a local variable 'name' to store the argument passed to the function.
    • Use "echo" to print a greeting message containing the provided name.

2.

Arithmetic Functions:

Write a Bash script that defines separate functions for addition, subtraction, multiplication, and division. These functions should take two numbers as arguments and print the result of the corresponding operation.

Code:

#!/bin/bash

# Function for addition
add() {
    local num1=$1
    local num2=$2
    local sum=$((num1 + num2))
    echo "The sum of $num1 and $num2 is: $sum"
}

# Function for subtraction
subtract() {
    local num1=$1
    local num2=$2
    local difference=$((num1 - num2))
    echo "The difference between $num1 and $num2 is: $difference"
}

# Function for multiplication
multiply() {
    local num1=$1
    local num2=$2
    local product=$((num1 * num2))
    echo "The product of $num1 and $num2 is: $product"
}

# Function for division
divide() {
    local num1=$1
    local num2=$2

    if [ $num2 -eq 0 ]; then
        echo "Error: Division by zero"
        exit 1
    fi

    local result=$(bc <<< "scale=2; $num1 / $num2")
    echo "The division of $num1 by $num2 is: $result"
}

# Test the functions
add 20 5
subtract 20 5
multiply 20 5
divide 20 5

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh
The sum of 20 and 5 is: 25
The difference between 20 and 5 is: 15
The product of 20 and 5 is: 100
The division of 20 by 5 is: 4.00 

Explanation:

In the exercise above,

  • Define four functions: "add", "subtract", "multiply", and "divide".
  • Each function takes two numbers as arguments and performs the corresponding operation.
  • For addition, subtraction, and multiplication, we simply perform the operation using arithmetic expansion ($((...))) and print the result.
  • For division, use "bc" command-line calculator to perform floating-point division with two decimal places (scale=2). We also handle division by zero error.
  • Finally test each function by calling them with example numbers.

3.

Factorial Function:

Write a Bash script that defines a function called factorial which calculates and prints the factorial of a given number.

Code:

#!/bin/bash

# Define the factorial function
factorial() {
    local num=$1
    local result=1

    # Check if num is negative
    if [ $num -lt 0 ]; then
        echo "Error: Factorial is not defined for negative numbers"
        exit 1
    fi

    # Calculate factorial
    for ((i = 1; i <= num; i++)); do
        result=$((result * i))
    done

    echo "The factorial of $num is: $result"
}

# Test the factorial function with a number
factorial 4
factorial 10

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh
The factorial of 4 is: 24
The factorial of 10 is: 3628800

Explanation:

In the exercise above,

  • Define a function called "factorial" using the factorial() { ... } syntax.
  • Inside the function:
    • Declare a local variable 'num' to store the argument passed to the function.
    • Declare another local variable 'result' and initialize it to 1.
    • Check if 'num' is negative. If it is, we print an error message and exit the script.
    • Next calculate the factorial of 'num' using a loop and store the result in the 'result' variable.

4.

Maximum and Minimum Functions:

Write a Bash script that defines functions called maximum and minimum which take two numbers as arguments and print the maximum and minimum of the two, respectively.

Code:

#!/bin/bash

# Function to find maximum of two numbers
maximum() {
    local num1=$1
    local num2=$2

    if [ $num1 -gt $num2 ]; then
        echo "The maximum of $num1 and $num2 is: $num1"
    else
        echo "The maximum of $num1 and $num2 is: $num2"
    fi
}

# Function to find minimum of two numbers
minimum() {
    local num1=$1
    local num2=$2

    if [ $num1 -lt $num2 ]; then
        echo "The minimum of $num1 and $num2 is: $num1"
    else
        echo "The minimum of $num1 and $num2 is: $num2"
    fi
}

# Test the maximum and minimum functions
maximum 101 201
minimum 12 17 

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh
The maximum of 101 and 201 is: 201
The minimum of 12 and 17 is: 12

Explanation:

In the exercise above,

  • Define two functions: "maximum()" and "minimum()".
  • Each function takes two numbers as arguments and compares them.
  • For "maximum()", if the first number is greater than the second, it prints the first number as the maximum; otherwise, it prints the second number as the maximum.
  • For "minimum()", if the first number is less than the second, it prints the first number as the minimum; otherwise, it prints the second number as the minimum.

5.

Power Function:

Write a Bash script that defines a function called power which takes two numbers as arguments and prints the result of raising the first number to the power of the second number.

Code:

#!/bin/bash

# Define the power function
power() {
    local base=$1
    local exponent=$2
    local result=$((base ** exponent))
    echo "The result of $base raised to the power of $exponent is: $result"
}

# Test the power function with two numbers
power 3 4
power 10 3

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh
The result of 3 raised to the power of 4 is: 81
The result of 10 raised to the power of 3 is: 1000

Explanation:

In the exercise above,

  • Define a function called "power()" using the power() { ... } syntax.
  • Inside the function:
    • Declare local variables 'base' and 'exponent' to store the arguments passed to the function.
    • Calculate the result of raising 'base' to the power of 'exponent' using the ** operator.
    • Finally, use "echo" to print a message showing the result.

6.

Prime Check Function:

Write a Bash script that defines a function called is_prime which checks if a given number is prime or not and prints the result.

Code:

#!/bin/bash

# Define the is_prime function
is_prime() {
    local num=$1
    local is_prime=true

    if [ $num -lt 2 ]; then
        is_prime=false
    else
        for ((i = 2; i <= num / 2; i++)); do
            if [ $((num % i)) -eq 0 ]; then
                is_prime=false
                break
            fi
        done
    fi

    if $is_prime; then
        echo "$num is prime"
    else
        echo "$num is not prime"
    fi
}

# Test the is_prime function with a number
is_prime 19
is_prime 22

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh
19 is prime
22 is not prime 

Explanation:

In the exercise above,

  • Define a function called "is_prime()" using the is_prime() { ... } syntax.
  • Inside the function:
    • Declare local variables 'num' and 'is_prime'.
    • First check if the number is less than 2. If it is, then it's not prime.
    • Otherwise, loop from 2 to half of the number. If the number is divisible by any number other than 1 and itself, it's not prime.
    • Based on the above checks, we set the 'is_prime' variable to true or false.
    • Print whether the number is prime or not based on the value of 'is_prime'.

7.

File Operations Functions:

Write a Bash script that defines functions for basic file operations like creating a file, deleting a file, and checking if a file exists.

Code:

#!/bin/bash

# Function to create a file
create_file() {
    local filename=$1
    touch "$filename"
    echo "File '$filename' created."
}

# Function to delete a file
delete_file() {
    local filename=$1
    if [ -f "$filename" ]; then
        rm "$filename"
        echo "File '$filename' deleted."
    else
        echo "File '$filename' does not exist."
    fi
}

# Function to check if a file exists
file_exists() {
    local filename=$1
    if [ -f "$filename" ]; then
        echo "File '$filename' exists."
    else
        echo "File '$filename' does not exist."
    fi
}
# Test the file operations functions
create_file "doc_file.txt"
file_exists "doc_file.txt"
delete_file "doc_file.txt"
file_exists "doc_file.txt"

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh
File 'doc_file.txt' created.
File 'doc_file.txt' exists.
File 'doc_file.txt' deleted.
File 'doc_file.txt' does not exist.

Explanation:

In the exercise above,

  • Define three functions: "create_file()", "delete_file()", and "file_exists()".
  • create_file function creates a file with the specified name using the "touch" command.
  • delete_file function deletes a file if it exists using the "rm" command, and prints a message accordingly.
  • file_exists function checks if a file exists using the -f test operator and prints a message accordingly.
  • Test these functions by creating a file, checking if it exists, deleting it, and checking again.

8.

String Manipulation Functions:

Write a Bash script that defines functions for common string manipulations such as string length, substring extraction, and string concatenation.

Code:

#!/bin/bash

# Function to get the length of a string
string_length() {
    local str=$1
    echo "Length of '$str' is: ${#str}"
}

# Function to extract a substring from a string
substring_extraction() {
    local str=$1
    local start=$2
    local length=$3
    local substring=${str:start:length}
    echo "Substring from position $start with length $length in '$str' is: $substring"
}

# Function to concatenate two strings
string_concatenation() {
    local str1=$1
    local str2=$2
    local concatenated="$str1$str2"
    echo "Concatenated string of '$str1' and '$str2' is: $concatenated"
}
# Test the string manipulation functions
string_length "Hello, world!"
substring_extraction "Hello, world!" 6 4
string_concatenation "Bash, " "Scripting!"

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh
./test1.sh: line 2: n: command not found
Length of 'Hello, world!' is: 13
Substring from position 6 with length 4 in 'Hello, world!' is:  wor
Concatenated string of 'Bash, ' and 'Scripting!' is: Bash, Scripting!

Explanation:

In the exercise above,

  • Define three functions: "string_length()", "substring_extraction()", and "string_concatenation()".
  • string_length function calculates the length of the given string using "${#str}" syntax.
  • substring_extraction function extracts a substring from the given string using the "${str:start:length}" syntax.
  • string_concatenation function concatenates two strings using simple string concatenation.

9.

Directory Operations Functions:

Write a Bash script that defines functions for working with directories, such as creating a directory, listing files in a directory, and checking if a directory exists.

Code:

#!/bin/bash

# Function to create a directory
create_directory() {
    local dirname=$1
    mkdir -p "$dirname"
    echo "Directory '$dirname' created."
}

# Function to list files in a directory
list_files() {
    local dirname=$1
    if [ -d "$dirname" ]; then
        echo "Files in directory '$dirname':"
        ls "$dirname"
    else
        echo "Directory '$dirname' does not exist."
    fi
}

# Function to check if a directory exists
directory_exists() {
    local dirname=$1
    if [ -d "$dirname" ]; then
        echo "Directory '$dirname' exists."
    else
        echo "Directory '$dirname' does not exist."
    fi
}
# Test the directory functions
create_directory "workarea_dir"
directory_exists "workarea_dir"
list_files "workarea_dir"

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh
Directory 'workarea_dir' created.
Directory 'workarea_dir' exists.
Files in directory 'workarea_dir':

Explanation:

In the exercise above,

  • Define three functions: "create_directory()", "list_files()", and "directory_exists()".
  • create_directory function creates a directory with the specified name using the mkdir command.
  • list_files function lists files in a directory if it exists, using the "ls" command.
  • directory_exists function checks if a directory exists using the -d test operator.
  • Finally, test these functions by creating a directory, checking if it exists, and listing files in it.

10.

Temperature Conversion Functions:

Write a Bash script that defines functions to convert temperatures between Celsius and Fahrenheit, and vice versa.

Code:

#!/bin/bash

# Function to convert Celsius to Fahrenheit
celsius_to_fahrenheit() {
    local celsius=$1
    local fahrenheit=$(echo "scale=2; ($celsius * 9/5) + 32" | bc)
    echo "$celsius°C is equal to $fahrenheit°F"
}

# Function to convert Fahrenheit to Celsius
fahrenheit_to_celsius() {
    local fahrenheit=$1
    local celsius=$(echo "scale=2; ($fahrenheit - 32) * 5/9" | bc)
    echo "$fahrenheit°F is equal to $celsius°C"
}

# Test the temperature conversion functions
celsius_to_fahrenheit 20
fahrenheit_to_celsius 68

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh
20°C is equal to 68.00°F
68°F is equal to 20.00°C

Explanation:

In the exercise above,

  • Define two functions: "celsius_to_fahrenheit()" and "fahrenheit_to_celsius()".
  • celsius_to_fahrenheit function converts Celsius temperature to Fahrenheit using the formula: (°Cx9/5)+32(°Cx5/9)+32.
  • fahrenheit_to_celsius function converts Fahrenheit temperature to Celsius using the formula: (°F-32)x5/9(°F-32)x9/5.
  • Use the "bc" command-line calculator with the 'scale' set to 2 to perform floating-point calculations.

Bash Editor:


More to Come !

Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.



Follow us on Facebook and Twitter for latest update.