w3resource

Bash Functions: Returning Values from Functions Exercises and Solutions

1.

Addition Function:

Write a Bash script that defines a function called add which takes two numbers as arguments and returns their sum using a recursive approach.

This problem involves writing a Bash script that defines a function named "add()" to calculate and return the sum of two given numbers using a recursive approach. The function should handle the addition by incrementing or decrementing the first number until the second number is exhausted, effectively performing the addition recursively.

Code:

#!/bin/bash

# Define the add function
add() {
    local num1=$1
    local num2=$2
    local sum=$((num1 + num2))
    echo "$sum"
}

# Test the add function
result=$(add 25 23)
echo "The sum is: $result"

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh
The sum is: 48

Explanation:

In the exercise above,

  • Define a function called "add()" using the add() { ... } syntax.
  • Inside the function:
    • Declare local variables 'num1' and 'num2' to store the arguments passed to the function.
    • Calculate the sum of 'num1' and 'num2' and store it in the 'sum' variable.
    • Use echo to output the value of sum.
  • Finally test the "add()" function by calling it with two numbers and storing the result in a variable 'result'.

2.

Subtraction Function:

Write a Bash script that defines a function called subtract which takes two numbers as arguments and returns their difference.

This problem involves writing a Bash script that defines a function named "subtract()" to calculate and return the difference between two given numbers. The function should take two arguments, subtract the second number from the first, and return the result.

Code:

#!/bin/bash

# Define the subtract function
subtract() {
    local num1=$1
    local num2=$2
    local difference=$((num1 - num2))
    echo "$difference"
}

# Test the subtract function
result=$(subtract 14 4)
echo "The difference is: $result"

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh
The difference is: 10

Explanation:

In the exercise above,

  • Define a function called "subtract()" using the subtract() { ... } syntax.
  • Inside the function:
    • Declare local variables 'num1' and 'num2' to store the arguments passed to the function.
    • Calculate the difference between 'num1' and 'num2' and store it in the difference variable.
    • Use "echo" to output the value of 'difference'.
  • Test the "subtract()" function by calling it with two numbers and storing the result in a variable 'result'.

3.

Multiplication Function:

Write a Bash script that defines a function called multiply that takes two numbers as arguments and returns their product.

This problem involves writing a Bash script that defines a function named "multiply()" to calculate and return the product of two given numbers. The function should take two arguments, multiply them, and return the result.

Code:

#!/bin/bash

# Define the multiply function
multiply() {
    local num1=$1
    local num2=$2
    local product=$((num1 * num2))
    echo "$product"
}

# Test the multiply function
result=$(multiply 6 7)
echo "The product is: $result"

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh
The product is: 42

Explanation:

In the exercise above,

  • Define a function called "multiply()" using the multiply() { ... } syntax.
  • Inside the function:
    • Declare local variables 'num1' and 'num2' to store the arguments passed to the function.
    • Calculate the product of 'num1' and 'num2' and store it in the 'product' variable.
    • Use "echo" command to output the value of 'product'.
  • Test the "multiply()" function by calling it with two numbers and storing the result in a variable 'result'.
  • Finally, we print the result.

4.

Division Function:

Write a Bash script that creates a function called divide that takes two numbers as arguments and returns their division.

This problem involves writing a Bash script that defines a function named "divide()" to calculate and return the division of two given numbers. The function should take two arguments, divide the first number by the second, and return the result. The script should also handle the case where division by zero is attempted.

Code:

#!/bin/bash

# Define the divide function
divide() {
    local dividend=$1
    local divisor=$2

    # Check if divisor is zero
    if [ $divisor -eq 0 ]; then
        echo "Error: Division by zero"
        exit 1
    fi

    local result=$(bc <<< "scale=2; $dividend / $divisor")
    echo "$result"
}

# Test the divide function
result=$(divide 100 4)
echo "The division result is: $result"

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh
The division result is: 25.00

Explanation:

In the exercise above,

  • Define a function called "divide()" using the divide() { ... } syntax.
  • Inside the function:
    • Declare local variables 'dividend' and 'divisor' to store the arguments passed to the function.
    • Check if the divisor is zero. If it is, we print an error message and exit the script.
    • Use "bc" command-line calculator to perform floating-point division with two decimal places (scale=2).
  • Test the "divide()" function by calling it with two numbers and storing the result in a variable 'result'.
  • Finally, we print the result.

5.

Factorial Function:

Write a Bash script that creates a function called factorial that calculates and returns the factorial of a given number.

This problem involves writing a Bash script that defines a function named "factorial()" to calculate and return the factorial of a given number. The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. The script should include a recursive or iterative approach to compute the factorial and then display the result.

Code:

#!/bin/bash

# Function to calculate factorial
factorial() {
  local n=$1
  if (( n <= 1 )); then
    echo 1
  else
    local temp=$(( n - 1 ))
    local result=$(factorial $temp)
    echo $(( n * result ))
  fi
}

# Read the number from user input
read -p "Enter a number: " num

# Validate if input is a non-negative integer
if [[ $num =~ ^[0-9]+$ ]]; then
  # Calculate and display the factorial
  result=$(factorial $num)
  echo "Factorial of $num is $result"
else
  echo "Please enter a non-negative integer."
fi

Output:

Enter a number: 4
Factorial of 4 is 24

Explanation:

In the exercise above,

  • Function definition:
    • The "factorial()" function takes one parameter (the number for which the factorial is to be calculated).
    • If the number is less than or equal to 1, it returns 1 (base case for recursion).
    • Otherwise, it recursively calls itself with the number decremented by 1 and multiplies the result by the current number.
  • User input:
    • The script prompts the user to enter a number.
    • It validates that the input is a non-negative integer.
  • Factorial calculation and output:
    • The script calls the "factorial()" function with user input and displays the result.

6.

Maximum Function:

Write a Bash script that creates a function named maximum which takes two numbers as arguments and returns the maximum of the two.

This problem involves writing a Bash script that defines a function named "maximum()" to determine and return the maximum of two given numbers. The script should include logic to compare the two input numbers and output the larger one.

Code:

#!/bin/bash

# Function to find the maximum of two numbers
maximum() {
  local num1=$1
  local num2=$2
  if (( num1 > num2 )); then
    echo $num1
  else
    echo $num2
  fi
}

# Read two numbers from user input
read -p "Enter the first number: " num1
read -p "Enter the second number: " num2

# Validate if inputs are numbers
if [[ $num1 =~ ^-?[0-9]+(\.[0-9]+)?$ ]] && [[ $num2 =~ ^-?[0-9]+(\.[0-9]+)?$ ]]; then
  # Calculate and display the maximum
  result=$(maximum $num1 $num2)
  echo "The maximum of $num1 and $num2 is $result"
else
  echo "Please enter valid numbers."
fi

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh
./test1.sh: line 2: n: command not found
Enter the first number: 12
Enter the second number: 10
The maximum of 12 and 10 is 12

Explanation:

In the exercise above,

  • Function definition:
    • The "maximum()" function is defined to take two parameters (the numbers to be compared).
    • It compares the two numbers using an "if" statement.
    • It returns the greater of the two numbers.
  • User Input:
    • The script prompts the user to enter two numbers.
    • It validates that the inputs are valid numbers (allowing for negative numbers and decimal points).
  • Maximum calculation and output:
    • The script calls the "maximum()" function with the user inputs and displays the result.

7.

Minimum Function:

Write a Bash script that creates a function called minimum which takes two numbers as arguments and returns the minimum of the two.

This problem involves writing a Bash script that defines a function named minimum to determine and return the minimum of two given numbers. The script should include logic to compare the two input numbers and output the smaller one.

Code:

#!/bin/bash

# Function to find the minimum of two numbers
minimum() {
  local num1=$1
  local num2=$2
  if (( num1 < num2 )); then
    echo $num1
  else
    echo $num2
  fi
}

# Read two numbers from user input
read -p "Enter the first number: " num1
read -p "Enter the second number: " num2

# Validate if inputs are numbers
if [[ $num1 =~ ^-?[0-9]+(\.[0-9]+)?$ ]] && [[ $num2 =~ ^-?[0-9]+(\.[0-9]+)?$ ]]; then
  # Calculate and display the minimum
  result=$(minimum $num1 $num2)
  echo "The minimum of $num1 and $num2 is $result"
else
  echo "Please enter valid numbers."
fi

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh
./test1.sh: line 2: n: command not found
Enter the first number: 23
Enter the second number: 21
The minimum of 23 and 21 is 21

Explanation:

In the exercise above,

  • Function definition:
    • The "minimum()" function is defined to take two parameters (the numbers to be compared).
    • It compares the two numbers using an "if" statement.
    • It returns the smaller of the two numbers.
  • User input:
    • The script prompts the user to enter two numbers.
    • It validates that the inputs are valid numbers (allowing for negative numbers and decimal points).
  • Minimum calculation and output:
    • The script calls the "minimum()" function with the user inputs and displays the result.

8.

Square Function:

Write a Bash script that creates a function named square which takes a number as an argument and returns its square.

This problem involves writing a Bash script that defines a function named "square()" to calculate and return the square of a given number. The script should include logic to multiply the number by itself and output the result.

Code:

#!/bin/bash

# Function to calculate the square of a number
square() {
  local num=$1
  echo $(( num * num ))
}

# Read a number from user input
read -p "Enter a number: " num

# Validate if the input is a number
if [[ $num =~ ^-?[0-9]+(\.[0-9]+)?$ ]]; then
  # Calculate and display the square
  result=$(square $num)
  echo "The square of $num is $result"
else
  echo "Please enter a valid number."
fi

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh
./test1.sh: line 2: n: command not found
Enter a number: 12
The square of 12 is 144

Explanation:

In the exercise above,

  • Function definition:
    • The "square()" function is defined to take one parameter (the number to be squared).
    • It calculates the square of the number by multiplying the number by itself.
    • It returns the result.
  • User input:
    • The script prompts the user to enter a number.
    • It validates that the input is a valid number (allowing for negative numbers and decimal points).
  • Square calculation and output:
    • The script calls the "square()" function with user input and displays the result.

9.

Power Function:

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

This problem involves writing a Bash script that defines a function named "power()" to calculate and return the result of raising one number to the power of another. The script should include logic to perform exponentiation using the provided base and exponent values.

Code:

#!/bin/bash

# Function to calculate the power of a number
power() {
  local base=$1
  local exponent=$2
  echo $(( base ** exponent ))
}

# Read the base and exponent from user input
read -p "Enter the base number: " base
read -p "Enter the exponent number: " exponent

# Validate if inputs are numbers
if [[ $base =~ ^-?[0-9]+(\.[0-9]+)?$ ]] && [[ $exponent =~ ^-?[0-9]+(\.[0-9]+)?$ ]]; then
  # Calculate and display the power
  result=$(power $base $exponent)
  echo "$base raised to the power of $exponent is $result"
else
  echo "Please enter valid numbers."
fi

Output:

dt@DESKTOP-3KE0KU4:~$ ./test1.sh
Enter the base number: 3
Enter the exponent number: 2
3 raised to the power of 2 is 9
dt@DESKTOP-3KE0KU4:~$ ./test1.sh
Enter the base number: 4
Enter the exponent number: 4
4 raised to the power of 4 is 256

Explanation:

In the exercise above,

  • Function definition:
    • The "power()" function is defined to take two parameters (the base and the exponent).
    • It calculates the result of raising the base to the power of the exponent using the ** operator.
    • It returns the result.
  • User input:
    • The script prompts the user to enter the base and exponent numbers.
    • It validates that the inputs are valid numbers (allowing for negative numbers and decimal points).
  • Exponentiation Calculation and Output:
    • The script calls the "power()" function with the user inputs and displays the result.

10.

Prime Check Function:

Write a Bash script that creates a function called "is_prime()" which takes a number as an argument and returns true if the number is prime and false otherwise.

This problem involves writing a Bash script that defines a function named "is_prime()" to check if a given number is prime. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The script should include logic to determine the primality of the number and return 'true' if it is prime and 'false' otherwise.

Code:

#!/bin/bash

# Function to check if a number is prime
is_prime() {
  local num=$1

  # Check if the number is less than 2 (not prime)
  if (( num < 2 )); then
    echo false
    return
  fi

  # Check divisibility from 2 to the square root of the number
  for (( i=2; i*i<=num; i++ )); do
    if (( num % i == 0 )); then
      echo false
      return
    fi
  done

  # If no divisors found, the number is prime
  echo true
}

# Read a number from user input
read -p "Enter a number: " num

# Validate if the input is a non-negative integer
if [[ $num =~ ^[0-9]+$ ]]; then
  # Check and display if the number is prime
  result=$(is_prime $num)
  echo "Is $num a prime number? $result"
else
  echo "Please enter a valid non-negative integer."
fi

Output:

dt@DESKTOP-3KE0KU4:~$ ./test1.sh
./test1.sh: line 2: n: command not found
Enter a number: 4
Is 4 a prime number? false
dt@DESKTOP-3KE0KU4:~$ ./test1.sh
./test1.sh: line 2: n: command not found
Enter a number: 13
Is 13 a prime number? true

Explanation:

In the exercise above,

  • Function definition:
    • The "is_prime()" function takes one parameter (the number to be checked for primality).
    • It first checks if the number is less than 2, returning 'false' if it is.
    • It then checks for divisibility from 2 up to the square root of the number. If any divisor is found, it returns 'false'.
    • If no divisors are found, it returns 'true'.
  • User input:
    • The script prompts the user to enter a number.
    • It validates that the input is a non-negative integer.
  • Primality check and output:
    • The script calls the "is_prime()" function with the user input and displays the result.

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/bash-script-exercises/returning-values-from-functions.php