Skip to content

Latest commit

 

History

History
80 lines (61 loc) · 2.23 KB

File metadata and controls

80 lines (61 loc) · 2.23 KB

Functions

Functions in shell scripting provide a way to organize code into modular and reusable blocks. This guide covers defining functions, passing arguments, and returning values.

Defining Functions

Functions are defined using the function keyword or simply by providing the function name followed by parentheses {}.

Example 1: Simple Function Definition

#!/bin/bash

# Define a simple function
welcome() {
  echo "Welcome to Shell Scripting!"
}

# Call the function
welcome

This script defines a function named welcome that prints a welcome message when called.

Example 2: Function with Parameters

#!/bin/bash

# Define a function with parameters
greet() {
  echo "Hello, $1 $2!"
}

# Call the function with arguments
greet "Keval" "Hingu"

Here, the function greet takes two parameters and prints a greeting message with the provided arguments.

Passing Arguments

Functions can accept parameters, allowing dynamic behavior based on user input.

Example 3: Using Function Parameters

#!/bin/bash

# Function with parameters
multiply() {
  result=$(( $1 * $2 ))
  echo "Result: $result"
}

# Call the function with arguments
multiply 5 3

In this example, the function multiply takes two arguments, multiplies them, and prints the result.

Returning Values

Functions can return values using the return statement.

Example 4: Returning Values from a Function

#!/bin/bash

# Function with return value
calculate() {
  local result=$(( $1 + $2 ))
  echo "Result from function: $result"
  return $result
}

# Call the function and capture the return value
result=$(calculate 8 4)
echo "Result outside function: $result"

Here, the function calculate returns the sum of two numbers, and the result is captured when calling the function.

Key Takeaways

  • Defining Functions: Functions are defined using the function keyword or by providing the function name followed by {}.
  • Passing Arguments: Functions can accept parameters, allowing dynamic behavior based on user input.
  • Returning Values: Functions can return values using the return statement. Experiment with these examples to understand the concepts of defining functions, passing arguments, and returning values in shell scripting.