FreeKB - Getting Started with functions
Bash Shell Scripting - Getting Started with functions

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

 

IMPORTANT

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 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 04be2 in the box below so that we can be sure you are a human.




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |