How To Write Bash Shell Script In Under 1 Hour

Shell Scripting is one of the basic skills for a sysadmin. If you can’t do it, you’ll end up frustrated a few years later when someone asks you to script something.

Bash shell is one of the standard shells in modern Linux and Unix systems. Like most shell scripts, Bash shell scripts can make your daily system admin life easier by automating many mundane and repetitive tasks.

This tutorial will teach you how to write simple shell scripts using real-life examples. I assume you have a basic programming understanding, including functions, loops, condition statements, etc. So, we will dive straight into developing shell scripts.

Prerequisites

You have essential programming skills.

If you don’t, there are plenty of resources on the Internet for you to learn, including Youtube.

You have a bash shell environment.

If you don’t have access to the Linux/Uni environment and still love your Windows, you can set up Cygwin or Windows Subsystem For Linux.

Basic Structure of A Bash Shell Script

#!/bin/bash

function doAction()
{
    echo "Starting....$1";
}

#Arguments to the script given
if [[ $# -gt 1 ]]
then
    for argument in "$@"
    do
        doAction "$argument";
    done
else
    
     	doAction "...";
fi

Generate a single checksum value for all the files inside a directory

The function summary() is only visible within the bash script. So, the command find will not able to see it. Therefore, we need to export the function.

#!/usr/bin/bash
############################################################################
#Find the checksum for all the files in a directory, as a single checksum
#value
############################################################################
summary (){
    echo "$(stat -c '%y' "$1") $(md5sum "$1")"
}
#Export the function so can use by the find command
export -f summary
#Arguments to the script given
if [[ $# -eq 1 ]]
then
        find $@ -type f -exec bash -c 'summary "$0"' {} \; | LC_ALL=C sort | md5sum
else
        echo "Please supply only one directory"
fi

Leave a Reply

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


The reCAPTCHA verification period has expired. Please reload the page.