w3resource

Bash Functions: Passing Arguments 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 "Pitter"

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh
Hello, Pitter! 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 25 30
subtract 12 14
multiply 4 7
divide 12 5

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh
The sum of 25 and 30 is: 55
The difference between 12 and 14 is: -2
The product of 4 and 7 is: 28
The division of 12 by 5 is: 2.40

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, we use "bc" command-line calculator to perform floating-point division with two decimal places (scale=2). We also handle division by zero error.

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 6
factorial 11

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh
./test1.sh: line 1: l: command not found
The factorial of 6 is: 720
The factorial of 11 is: 39916800

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 we 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 200 150
minimum 12 11

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh
The maximum of 200 and 150 is: 200
The minimum of 12 and 11 is: 11

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 2 3
power 10 2

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh
The result of 2 raised to the power of 3 is: 8
The result of 10 raised to the power of 2 is: 100

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, "echo" command is used to print a message showing the result.

6.

From Wikipedia, the free encyclopedia
A twin prime is a prime number that is either 2 less or 2 more than another prime number-for example, either member of the twin prime pair (17, 19) or (41, 43). In other words, a twin prime is a prime that has a prime gap of two. Sometimes the term twin prime is used for a pair of twin primes; an alternative name for this is prime twin or prime pair.

Twin Prime Check Function:

Write a Bash script that defines a function called is_twin_prime which checks if two given numbers are twin prime or not and prints the result.

Code:

#!/bin/bash

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

    # Check if num is less than 2
    if [ $num -lt 2 ]; then
        return 1
    fi

    # Check if num is divisible by any number from 2 to sqrt(num)
    for ((i = 2; i * i <= num; i++)); do
        if [ $((num % i)) -eq 0 ]; then
            return 1
        fi
    done

    # If no divisor found, num is prime
    return 0
}

# Define the is_twin_prime function
is_twin_prime() {
    local num1=$1
    local num2=$2

    # Check if both numbers are prime and have a difference of 2
    if is_prime "$num1" && is_prime "$num2" && [ $((num2 - num1)) -eq 2 ]; then
        echo "$num1 and $num2 are twin primes"
    else
        echo "$num1 and $num2 are not twin primes"
    fi
}

# Test the is_twin_prime function with two numbers
is_twin_prime 3 5
is_twin_prime 11 13
is_twin_prime 9 11

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh
3 and 5 are twin primes
11 and 13 are twin primes
9 and 11 are not twin primes

Explanation:

In the exercise above,

  • Define a function called "is_prime()" to check if a number is prime.
  • Define another function called "is_twin_prime()" to check if two numbers are twin primes.
  • The "is_prime()" function checks if a number is prime by iterating from 2 to the square root of the number.
  • The "is_twin_prime()" function checks if both numbers are prime and have a difference of 2.

7.

String Manipulation Functions:

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

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!" 4 3
string_concatenation "Bash, " "Script!"

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh
Length of 'Hello, world!' is: 13
Substring from position 4 with length 3 in 'Hello, world!' is: 'o, '
Concatenated string of 'Bash, ' and 'Script!' is: 'Bash, Script!' 

Explanation:

In the exercise above,

  • We 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.

8.

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. Pass file names as arguments to these functions.

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 -p 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.
  • We test these functions by creating a directory, checking if it exists, and listing files in it.

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.