< back to $HOME

Code Snippets (bash)

Here's some various code snippets I refer to when writing scripts. It saves a lot of time when I have them all in one place, rather than wasting time looking for them on Google..

I'll be adding more as time goes on. I have a ton of snippets, so this will grow (eventually..)

Use a variable when checking multiple things (i.e. 2 or more files/procs exist, etc.)


#!/bin/bash

# Change the values of foo and/or bar to see what happens.

# Valid values are 0 or 1
foo="0"
bar="0"

if [ "$foo" = "0" ]; then
        echo "Foo is normal."
	else
        	echo "Houston, we have a problem - Foo is borked."
        	status="1"
fi

if [ "$bar" = "0" ]; then
        echo "Bar is normal."
	else
        	echo "Houston, we have a problem - Bar is borked."
        	status="1"
fi


if [ "$status" = "1" ]; then
        echo "Something somewhere is borked."
	else
        	echo "Everything seems to be OK."
fi

# A sample usage is to check to make sure 2 procs are running:

if [ -e /var/run/myproc.pid ]; then
	echo "My proc is running - pid `cat /var/run/myproc.pid`"
	else
		echo "Sound the alarm!  myproc is not running!"
		alert="1"
fi

if [ -e /var/run/myproc2.pid ]; then
	echo "My proc2 is running - pid `cat /var/run/myproc2.pid`"
	else
		echo "Sound the alarm!  myproc2 is not running!"
		alert="1"
fi

if [ "$alert" = "1" ]; then
	send in the Marines!
	else
		echo "Everything is OK."
fi


Date variables:


#!/bin/sh
# Define the DATE variable for logging

mydate=`date +'%Y-%m-%d %H:%M:%S'`

-OR-

mydate=`date +'%Y-%m-%d'`
yesterday=`date -v-1d +'%Y-%m-%d'`
lastmonth=`date -v-1m +'%Y-%m'`


Test for the existence of a file:


#!/bin/bash

# Test for the existance of a file.

file=foo.txt

if [ -e "$file" ]; then
        echo "Yup, it's here."
else
        echo "Sorry, file not found."
fi


Create a function for logging:


function log {
         NOW=$(date +'%Y-%m-%d %H:%M:%S')
         echo "${NOW} - ${1}" >> sample_log.log
}

# Usage: log "This is a log entry."


< back to $HOME