Many programming languages use functions to organize their code. A function is a block of code with a name. It is often the case that the same code, or very similar code, is needed in multiple different contexts. Instead of typing out the same code in each context, the code can go in a function and the function can be called by its name. Functions usually accept input parameters and generate a return value.
Linux shell scripts support functions. Because shell scripts are interpreted, the function definitions must appear in the script before any calls to the function. Functions are defined by their name followed by open and closed parenthesis. Function calls in shell scripts work the same as running commands. The function is called by its name without the parenthesis. The function parameters are the arguments that appear after the name, and they are passed to the function the same way arguments are passed to a shell script (using the $1, $2, etc… variables). Like commands, functions can have exit codes which are set by using the ‘return’ keyword. The following example shows how to use functions in a Linux shell script:
food.sh
#!/bin/sh
# function declaration taste_food() { # $1 is the first argument passed to this function if [ $1 == rotten ] then echo “It was thrown away.” return 1 # Exit code for failure fi echo “It was eaten.” return 0 # Exit code for success }
# function declaration give_me_food() { # $@ is all of the arguments passed to this function echo “Received $@.”
# function call, ‘if’ checks the function’s exit code if taste_food $@ then echo “Yum!” else echo “Yuck.” fi }
# function calls give_me_food apple give_me_food rotten tomato |
Output:
> ./food.sh Received apple. It was eaten. Yum! Received rotten tomato. It was thrown away. Yuck. |