Create and use functions

To create and use functions in shell scripts, you can follow these steps:

  • Define the function: The syntax for defining a function is as follows:

function_name() {
# function code here
}

You can name the function whatever you like, as long as it doesn’t contain any whitespace.

  • Write function code: Within the function code block, you can write the commands you want to execute.
  • Call the function: to call the function, just write its name followed by parentheses.

Here’s an example of how to create and use a function in a shell script:

# define the function
show_message() {
echo “This is a sample message”
}

#Call the function
show_message

When running this script, the message “This is a sample message” will be displayed on the standard output.

You can also pass parameters to a function in the shell. To do this, simply define the parameters inside the parentheses in the function definition and refer to them by name when executing the function. Here is an example:

#define the function
salute() {
name=$1
echo “Hello, $name! How are you?”
}

#Call the function with a parameter
salute “John”

In this example, the “salute” function takes a name parameter, which is used to display a custom greeting on standard output. When calling the function with the “John” parameter, the output will be “Hello, John! How are you?”.