Skip to content

Bash Code

spsammy edited this page Apr 6, 2018 · 9 revisions

Table of Contents

Directory of the script

Get the absolute directory of the script.

absScriptDir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"; # get the absolute path to this file's directory
 
source "$absScriptDir/conf/$(hostname).config"

Checks

Check script arguments

Fixed number of parameters

# Check for proper number of command line args.
EXPECTED_ARGS=1
E_BADARGS=65

if [ $# -ne $EXPECTED_ARGS ]
then
  echo "Usage: `basename $0` minutes"
  echo "Usage: `basename $0` 5"
  echo "Usage: `basename $0` 1"
  exit $E_BADARGS
fi

Variable number of parameters

MIN_EXPECTED_ARGS=1
MAX_EXPECTED_ARGS=3
E_BADARGS=65
if [ $# -lt $MIN_EXPECTED_ARGS ] || [ $# -gt $MAX_EXPECTED_ARGS ]
then
  echo "Usage: `basename $0` debug-level [dontwipe] [html-colour]"
  echo "Usage: `basename $0` debug"
  echo "Usage: `basename $0` debug dontwipe html-colour"
  echo "Usage: `basename $0` info"
  echo "Usage: `basename $0` warning"
  echo "Usage: `basename $0` error"
  echo "Debug flag is mandatory. If 'dontwipe' appears then we skip the question to delete existing files (we do not delete). html-colour should be used to output html colour instead of tput codes ";
  exit $E_BADARGS
fi

Check function arguments

  1. Create this sanity check function
################################################################################
# Function to test if a variable has a value or not. If there is not value, we
# output an error to the log.
#
# Use like:
#     sanity_check  "sectionName";
#
# variable_name: the name of the variable to test. Should not have the $ sign. e.g. "startId"
#
# Nothing returned.
function sanity_check(){
    local variable_name=$1;
    local command="$";
    command+="$variable_name";
    local value;
    eval "value=$command";
    if [ ! -n "$value" ];
    then
        log_error "Error! $yellow[$variable_name]$reset is undefined!";
    fi
}
  1. Use it like so
function process {
    local table_name=$1;
    local table_columns=$2;
    local sectionName=$3;
    local filename=$4;
    # Sanity check the inputs
    sanity_check  "table_name";
    sanity_check  "table_columns";
    sanity_check  "sectionName";
    sanity_check  "filename";


...
 
}

Check a command is installed

function test_command_installed(){
	
lockfile -v  || { echo >&2 "$red I require lockfile but it's not installed. 'yum install procmail' to get it.  Aborting. $reset"; exit 1;}
}

Check for Sudo

if [ "$EUID" -ne 0 ];                                                                                                  
then                                                                                                                    
    echo "Should be run as sudo";                                                                                       
    exit                                                                                                                
fi

Output colours

# Do not set tput if the terminal can not cope
colour_check=$(tput colors 2> /dev/null );
if [ "$colour_check" != "" ];
then
    # For colours
    red=$(tput setaf 1);
    green=$(tput setaf 2);
    blue=$(tput setaf 4);
    yellow=$(tput setaf 3);
    purple=$(tput setaf 5);
    cyan=$(tput setaf 6);
    white=$(tput setaf 7);
    reset=$(tput sgr0);
fi

echo "$green Everything passed! $reset";

Specify

How To Specify Temp Files

  1. Putting files in /var/tmp means they will be automatically deleted after 30 days.
  2. Create a temp file with a random number in the name.
    tempFile=./tempfile.$RANDOM.tmp
  3. Create a temp file with the date-time in it.
    tempFile=$(date +%Y%m%d%H%M%S).tmp

How to Specify Temp Dir

TMP_DIR=$(mktemp -d 2>/dev/null || mktemp -d -t 'mytmpdir') # from https://unix.stackexchange.com/questions/30091/fix-or-alternative-for-mktemp-in-os-x

Date & Time

Echo Current Date and Time

echo "$(date +%Y-%m-%d\ %H:%M:%S)";

Compute Time Elapsed

# Measure how long it takes
start_time=$(date +%s);
...
 
finish_time=$(date +%s)
timetaken=$((finish_time - start_time));