How to pass parameters to functions?

066

In shell scripting, you can pass parameters to functions just like you would with command-line arguments. Here’s how to do it:

Defining a Function with Parameters

You can define a function that accepts parameters using the following syntax:

function_name() {
    # Access parameters using $1, $2, etc.
    echo "Parameter 1: $1"
    echo "Parameter 2: $2"
}

Calling the Function with Arguments

When you call the function, you can pass arguments like this:

function_name "Hello" "World"

Accessing Parameters

Inside the function, you can access the parameters using special variables:

  • $1: The first parameter
  • $2: The second parameter
  • $3: The third parameter
  • "$@": All parameters as a list
  • "$*": All parameters as a single word

Example

Here’s a complete example of a shell script that defines a function and passes parameters to it:

#!/bin/bash

greet() {
    echo "Hello, $1!"
    echo "Welcome to $2."
}

# Call the function with parameters
greet "Alice" "Wonderland"

Output

When you run the script, the output will be:

Hello, Alice!
Welcome to Wonderland.

This demonstrates how to define a function, pass parameters to it, and access those parameters within the function.

0 Comments

no data
Be the first to share your comment!