In part 1 and 2 we have presented the script outline and config section. Now to introduce helper functions.
First is usage
## Usage
function usage() {
clear
cat << USAGE
NAME
deploy - deploy projects to servers
SYNOPSIS
./deploy.sh PROJECT_NAME [-t|--target] TARGET [--tag] [-d|dump]
./deploy.sh PROJECT_NAME [-t|--target] [-m|--maintenance]
./deploy.sh PROJECT_NAME [-t|--target] [-d|--dump]
DESCRIPTION
Deploy Drupal projects (${_PROJECTS[@]}) to production.
Mandatory arguments to long options are mandatory for short options too.
-t, --target production or hostname for stageing
-m, --maintenance put destination server to maintance mode
-d, --dump make backup of project database at target
-f, --features list of features to revert
-h, --help display this help and exit
--tag tag to deploy
--force force command (i.e. dump on master)
EXAMPLES
Deploy to production from tag on master branch and make db backup
/deploy.sh project1 -t production --tag 20120829 -d
Put production to maintenance mode
/deploy.sh project1 -t production -m
Doploy development branch to staging server
/deploy.sh -t project1 --tag user/branch
AUTHOR
Written by Author1, Author2, Author3
USAGE
}
Since the example is an extract of deploy script help will usage will return something related to the functionality. This function is quite simple, only cool thing about it is that we listed array elements with ${_PROJECTS[@]}, to display projects available
For input validation we can use something like script bellow since as mentioned in previous post I believe its a good practice to be able to run script without parameters and get usage.
## Validate input
function validate_input() {
# Exit if there is some invalid arguments
if [ $# -lt 3 ]; then
usage
exit 0
fi
#if first argument is not project name show usage
in_array $1 "${_PROJECTS[@]}" && return 0 || usage; exit;
}
Function above checks if function has at least one parameter, which most be the project name
For debug output to console we can use something like:
#output messages to console
function debug() {
local _LEVEL=0
case "$1" in
ERROR )
_LEVEL=2 ;;
INFO )
_LEVEL=1 ;;
DEBUG )
_LEVEL=0 ;;
esac
if [ $_DEBUG -gt 0 ] && [ $_LEVEL -ge $_DEBUG_LEVEL ]
then
while [ $# -ne 0 ]; do
echo -n " $1"
shift
done
echo
fi
return 0
}
Good place to put these things is separate file in order to keep code clean.
To have full working project you will probably need at least function to become sudo or to catch user input.