10 useful shell script code snippets | Linux

10+ useful code snippets of Linux shell scripts for how-to color, sendmail, log, change dir, parse parameters, loop, configuration file, switch..case and more.

This post is collection of 10 useful unix / linux shell script code snippets I’ve often used.

Following these code snippet you will be able to answer following questions:
1. How to calculate script run-time in shell.
2. How to parse parameters / arguments to shell script.
3. How to safely change a directory in shell script.
4. How to check if a command was successful in shell script.
5. How to add timestamps in script log output.
6. How to check if a process is running.
7. How to colour your script output.
8. How to read variables from config file.
9. How to loop over files in a folder.
10. How to perform actions based on variable value using SWITCH…CASE

And a bonus snippet
11: How to send emails from shell script.

Let’s begin.

1. Snippet for calculating script run-time:

It’s always good to note the script duration and having knowledge of the run-time. Following is the code snippet for noting the script execution time.

Add this to the beginning of the script:

START=$(date +%s)

Add following at the end or exit location:

END=$(date +%s)
DIFF=$(( $END - $START ))
DIFF=$(( $DIFF / 60 ))

$DIFF will give you the runtime of the script in minutes.

2. Parsing & processing script parameters / arguments:

Scripts are often required to have user inputs in terms of arguments passed after script. Below code snippet is a simple method to capture the arguments passed.

while [ "$1" != "" ]; do
    case $1 in
        -s  )   shift	
		SERVER=$1 ;;  
        -d  )   shift
		DATE=$1 ;;
	--paramter|p ) shift
		PARAMETER=$1;;
        -h|help  )   usage # function call
                exit ;;
        * )     usage # All other parameters
                exit 1
    esac
    shift
done

Above snippet in shell script paramter_test.sh will behave as follows:

sh parameter_test.sh -s myserver -d 20151225 --parameter SomeValue

Though we may need to check for correctness of input or mandatory parameters; using say a parser function.
# Confirm the mandatory parameters

if [ -z $SERVER ] || [ -z $DATE ]; then
	echo "Please specify both server and date";
	exit 1;
fi;

3. Change directory before processing your script:

Sanitizing & verifying the directory status is very important before progressing the script. You do not want to mistakenly execute the commands in a wrong directory. We should verify if directory is present and have sufficient permission for the user.
Following code snippet takes care of the same.

changedir()
{
	DIR_NAME=$1
	# Check if the directory exist?
	[ -d "$DIR_NAME" ] || {
		echo Dir: $DIR_NAME does not exist 
		exit 1
	}

	# Check if the directory is readable
	[ -r "$DIR_NAME" ] || {
		echo Dir: $DIR_NAME not readable
		exit 2
	}

	# Check if we have execute perms on directory
	[ -x "$DIR_NAME" ] || {
		echo Dir: cannot cd to $DIR_NAME
		exit 3
	}

	# Check if the directory is writable
	[ -w "$DIR_NAME" ] || {
		echo Dir: $DIR_NAME not writeable
		exit 4
	}

	cd $DIR_NAME
	echo "Present directory $DIR_NAME"
}

To safely change the directory call the function as follows:

changedir /data/app/

4. Verifying if previous command was successful

When a processing of command depends on success or failure of previous command we can use the exit status. It can be checked using $?.

if [ $? -ne 0 ]; then
	echo "The command was not successful.";
	#do the needful / exit
fi;

5. Generating script logs with timestamp

Just as the duration of script it’s useful to have timestampped log. Use following function to log time for every output.

log() {
     echo [`date +%Y-%m-%d\ %H:%M:%S`] $*
}

Call the function as follows instead of simply “echo”ing.

log "my string to be logged"

6. Checking if process is running:

This code snippet is used often when a script progress requires the known status of any particular system process.
A usual scenario say we need MySQL down before progressing further in script, we will use following shell function.

# Define shell function
check_process() {
	echo "Checking if process $1 exists..."
	[ "$1" = "" ]  && return 0
	PROCESS_NUM=$(ps -ef | grep "$1" | grep -v "grep" | wc -l)
	if [ $PROCESS_NUM -ge 1 ];
	then
	        return 1
	else
	        return 0
	fi
}

# Check for MySQL process and make the decision

check_process mysql;
CHECK_RET=$?;
if [ $CHECK_RET -ne 0 ]; 
	# code block for process exists 
else
	# code block for process not present
fi;

7. Colouring your script output

A readable and formatted output is good to have. Following code snippet helps you beautify your script output, colorizing or highlighting them.

Define variables:
txtund=$(tput sgr 0 1)    # Underline
txtbld=$(tput bold)       # Bold
txtred=$(tput setaf 1)    # Red
txtgrn=$(tput setaf 2)    # Green
txtylw=$(tput setaf 3)    # Yellow
txtblu=$(tput setaf 4)    # Blue
txtpur=$(tput setaf 5)    # Purple
txtcyn=$(tput setaf 6)    # Cyan
txtwht=$(tput setaf 7)    # White
txtrst=$(tput sgr0)       # Text reset

Use them as:
echo "${txtbld}This is bold text output from shell script${txtrst}"
echo "${txtred}This is coloured red except ${txtblu}this is blue${txtrst}"

${txtrst} will reset the terminal.

Refer: http://kedar.nitty-witty.com/how-to-echo-colored-text-in-shell-script

8. Reading variables from config file

Create a config file with contents as follows:

key1=value1
key2=value2

Add following line in the beginning of the shell script:

. configfile

This will load the key value pairs and you may verify & access the values as $key1 or $key2.

9. Looping over files in a folder

Below code snippet is quite simple as a concept of FOR loop we might need to loop over the files to perform operations.

#!/bin/bash
PATH=/path/to/dir/
FILES=*.sql
for f in $PATH$FILES
do
	# Code block for processing each file $f
done

10. Using SWITCH…CASE

Following code snippet is a SWITCH…CASE for shell script often used for taking actions based on variable value.

	case $VARIABLE in
		VALUE-1) # CODE BLOCK FOR VALUE-1
			;;

		VALUE-2|VALUE-3) 
			# CODE BLOCK FOR VALUE-2 OR VALUE-3
		 	;;

		*) echo "Wrong option, exiting.";;
	esac

(Bonus solution to – how-to-send-email worries!)

11. The sendEmail Function

Following is the ready to use sendEmail function for your shell scripts. You may put the function definition in the beginning of your shell script and use to send emails.
All you need to set is variable values for email-content ($content), email-subject ($subject) and email-list ($email_list). Rest is only making a call to the function (sendEmail).
This handy function also notes the script runtime.

# sendEmail Function - mail & exit.
START=$(date +%s)
sendEmail() {
	scripttime=0;
	END=$(date +%s)
	DIFF=$(( $END - $START ))
	if [ $DIFF -le 60 ]; then
		scripttime="$DIFF seconds.";
	else
		DIFF=$(( $DIFF / 60 ))
		scripttime="$DIFF minutes.";
	fi;
	content="$content. Exec Time: $scripttime"
	echo $content | mail -s "$subject" $email_list
	exit;
}
# sendEmail Function - end.

Hope this helps.

Leave a Reply

Your email address will not be published. Required fields are marked *