Bash Shell Script Function Examples

www.lau‮t‬turi.com
Bash Shell Script Function Examples

Bash shell scripts support functions, which allow you to group related commands and statements, and perform operations on the data passed to the function.

Here are some examples of functions in Bash shell scripts:

  1. A simple function that prints a message to standard output:
#!/usr/bin/env bash

# Define the function
hello() {
  echo "Hello, world!"
}

# Call the function
hello

This function, called hello, simply prints the message "Hello, world!" to standard output. The function is defined using the function_name() { ... } syntax, and is called using the function name followed by any necessary arguments.

  1. A function that takes a string argument and prints it to standard output:
#!/usr/bin/env bash

# Define the function
greet() {
  echo "Hello, $1!"
}

# Call the function with an argument
greet "John"

This function, called greet, takes a string argument and prints a message using the argument. The function is defined using the function_name() { ... } syntax, and is called using the function name followed by the desired argument (in this case, "John"). The argument is accessed inside the function using the $1 variable, which represents the first argument passed to the function.

  1. A function that takes two arguments and performs a calculation:
#!/usr/bin/env bash

# Define the function
sum() {
  result=$(( $1 + $2 ))
  echo "$1 + $2 = $result"
Created Time:2017-10-16 14:38:38  Author:lautturi