Bootstrap FreeKB - Bash (Scripting) - Getting Started with functions
Bash (Scripting) - Getting Started with functions

Updated:   |  Bash (Scripting) articles

A function contains a segment of code that performs a certain task. In this example, the "printDate" function will print the current date.

function printDate {
  echo $(date +%m-%d-%Y)
}

 

Functions can also be created using this syntax.

printDate() {
  echo $(date +%m-%d-%Y)
}

 

Now, you can use the function in the script. In this example, instead of having to echo the date, you simply use the function.

printDate

 

AVOID TROUBLE

Functions must be created before the function is called.

This script will fail, because the printDate function is called before the printDate function is created.

#!/bin/bash

printDate

function printDate {
  echo $(date +%m-%d-%Y)
}

 

This script will executed as expected, as the printDate function is created, then the printDate function is called.

#!/bin/bash

function printDate {
  echo $(date +%m-%d-%Y)
}

printDate

 


Passing values into a function

One of the most powerful capabilities of a function is being able to pass values into the function. For example, this function use $1 to print the first value passed into the function (Hello World) and $2 to print the second value (Greetings).

function my_function {
  echo $1
  echo $2
}

 

Values are passed into a function by following the function with the values.

my_function "Hello World" "Greetings"

 


Return a value

And here is an example of how you can have a function that returns a value. Check out my article Bash (Scripting) Returning values from a function for more details on this.

#!/bin/bash

function request {
  echo hello
}

response=$(request)

echo "response = $response"

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 012e13 in the box below so that we can be sure you are a human.