Chapter 7: Functions

Declaring Functions

1 function_name () {
2 
3 	# code block
4 }
5 
6 # Calling the function
7 function_name

Function Parameters

We may send data to the function in a similar way to passing command line arguments to a script. We supply the arguments directly after the function name. Within the function they are accessible as $1, $2.. etc

 1 #!/usr/bin/env bash
 2 
 3 prompt_user () {
 4 
 5 	message={1:-"Hello World"}
 6 	echo "$message"
 7 }
 8 
 9 # No argument provided - default value for message will b\
10 e used
11 prompt_user
12 
13 # Argument provided
14 prompt_user "How are you?"

Return Values

Unlike programming languages, Bash does not allow functions to return values - it does however allow us to set a return status. Similar to how a program or command exits with an exit status which indicates whether it succeeded or not. We use the keyword return to indicate the return status:

  • Typically a return status of 0 indicates that everything went successfully.
  • A non zero value indicates an error occurred.