How to pass variables to functions?

0122

In shell scripts, you can pass variables to functions by using positional parameters. Here's how to do it:

  1. Define the Function: Create a function that takes parameters.

    my_function() {
        echo "Parameter 1: $1"
        echo "Parameter 2: $2"
    }
    
  2. Call the Function with Arguments: When you call the function, provide the arguments you want to pass.

    my_function "Hello" "World"
    
  3. Accessing Parameters: Inside the function, you can access the passed arguments using $1, $2, etc., where $1 is the first argument, $2 is the second, and so on.

  4. Example Script:

    #!/bin/bash
    
    # Define a function that takes two parameters
    greet() {
        echo "Hello, $1!"
        echo "Welcome to $2."
    }
    
    # Call the function with arguments
    greet "Alice" "Linux"
    

In this example, when you run the script, it will output:

Hello, Alice!
Welcome to Linux.

This demonstrates how to pass and use variables in functions in a shell script.

0 Comments

no data
Be the first to share your comment!