In shell scripts, you can pass variables to functions by using positional parameters. Here's how to do it:
Define the Function: Create a function that takes parameters.
my_function() { echo "Parameter 1: $1" echo "Parameter 2: $2" }Call the Function with Arguments: When you call the function, provide the arguments you want to pass.
my_function "Hello" "World"Accessing Parameters: Inside the function, you can access the passed arguments using
$1,$2, etc., where$1is the first argument,$2is the second, and so on.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.
