FreeKB - How to use functions in BASH
How to use functions in BASH

Home > Search > How-to

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.



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 execution {
  echo $1
  echo $2


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

execution "Hello World" "Greetings"


Add a Comment

We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.

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