BASH Functions

December 21, 2011

If you have repetitive code inside a bash script, it's possible to abstract it out into a function. Here's an example used for backing up postgres databases, and compressing the resulting sql file.

#!/bin/bash

export FILENAMEDATE=`date +%Y%m%d-%H%M%S`

function backup {
  export DATABASE=$1
  export USER=$2

  echo $DATABASE

  pg_dump -U $DATABASE $DATABASE > /home/$USER/db/$DATABASE-$FILENAMEDATE.sql
  gzip /home/$USER/db/$DATABASE-$FILENAMEDATE.sql
}

backup database1 drumcoder
backup database2 drumcoder
backup database3 drumcoder
backup database4 otheruser

Tags: bash function