Shell Scripting Tutorial (Part -4) Real World Bash Scripts |Learn Shell Scripting 2021

FreakyDodo
4 min readJun 11, 2021

--

This guide presents some of the advanced capabilities of the bash shell by showing practical and fully functional bash scripts. It also illustrates how you can work with dates and times in bash scripts and how to write and use functions in bash.

Working with Dates and Times

Bash allows you to work with dates and times using traditional UNIX utilities such as date(1). The main difficulty many programmers run into when working with dates and times is getting or using the correct format. This is a matter of using date(1) with the correct parameters and has nothing to do with bash scripting per se. Using date(1) as date +[something] means that we want to use a custom format – this is signified by the use of + in the command line argument of date(1).

A good way to create unique filenames is to use UNIX epoch time or, if you want your filename to be more descriptive, a date-time combination. The unique nature of the filename is derived from a focus on a higher level of detail in defining your output. If done correctly, you will never have the exact same time value even if you execute the script multiple times on the same UNIX machine.

The example that follows will shed some light on the use of date(1).

Using Dates and Times in bash scripts

The code of dateTime.sh is the following: File: dateTime.sh

#!/bin/bash# Print default output
echo `date`
# Print current date without the time
echo `date +"%m-%d-%y"`
# Use 4 digits for year
echo `date +"%m-%d-%Y"`
# Display time only
echo `date +"%T"`
# Display 12 hour time
echo `date +"%r"`
# Time without seconds
echo `date +"%H:%M"`
# Print full date
echo `date +"%A %d %b %Y %H:%M:%S"`
# Nanoseconds
echo Nanoseconds: `date +"%s-%N"`
# Different timezone by name
echo Timezone: `TZ=":US/Eastern" date +"%T"`
echo Timezone: `TZ=":Europe/UK" date +"%T"`
# Print epoch time - convenient for filenames
echo `date +"%s"`
# Print week number
echo Week number: `date +"%V"`
# Create unique filename
f=`date +"%s"`
touch $f
ls -l $f
rm $f
# Add epoch time to existing file
f="/tmp/test"
touch $f
mv $f $f.`date +"%s"`
ls -l "$f".*
rm "$f".*

If you want an even more unique filename, you can also use nanoseconds when defining the behaviour of your script.

https://mrscriptkiddie.com/what-is-shell-scripting/

Run the dateTime script:

./dateTime.sh

The output of dateTime.sh will resemble the following:

Fri Aug 30 13:05:09 EST 2019
08-30-19
08-30-2019
13:05:09
01:05:09 PM
13:05
Friday 30 Aug 2019 13:05:09
Nanoseconds: 1567159562-373152585
Timezone: 06:05:09
Timezone: 10:05:09
1567159509
Week number: 35
-rw-r--r-- 1 mtsouk staff 0 Aug 30 13:05 1567159509
-rw-r--r-- 1 mtsouk wheel 0 Aug 30 13:05 /tmp/test.1567159509

Watching Free Disk Space

The bash script that follows watches the free space of your hard disks and warns you when that free space drops below a given threshold — the value of the threshold is given by the user as a command line argument. Notice that if the program gets no command line argument, a default value is used as the threshold.

https://mrscriptkiddie.com/what-is-shell-different-types-of-linux-shell-shell-scripting-tutorial-part-1/

#!/bin/bash# default value to use if none specified
PERCENT=30
# test for command line arguement is present
if [[ $# -le 0 ]]
then
printf "Using default value for threshold!\n"
# test if argument is an integer
# if it is, use that as percent, if not use default
else
if [[ $1 =~ ^-?[0-9]+([0-9]+)?$ ]]
then
PERCENT=$1
fi
fi
let "PERCENT += 0"
printf "Threshold = %d\n" $PERCENT
df -Ph | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5,$1 }' | while read data;
do
used=$(echo $data | awk '{print $1}' | sed s/%//g)
p=$(echo $data | awk '{print $2}')
if [ $used -ge $PERCENT ]
then
echo "WARNING: The partition \"$p\" has used $used% of total available space - Date: $(date)"
fi
done
  • The sed s/%//g command is used for omitting the percent sign from the output of df -Ph.
  • df is the command to report file system disk space usage, while the options -Ph specify POSIX output and human-readable, meaning, print sizes in powers of 1024.
  • awk(1) is used for extracting the desired fields from output of the df(1) command.

Run ./freeDisk.sh with this command:

./freeDisk.sh

The output of freeDisk.sh will resemble the following:

Using default value for threshold!
Threshold = 30
WARNING: The partition "/dev/root" has used 61% of total available space - Date: Wed Aug 28 21:14:51 EEST 2019

The bash scripting language is a powerful programming language that can save you time and energy when applied effectively. If you have a lot of useful bash scripts, then you can automate things by creating cron jobs that execute your bash scripts. It is up to the developer to decide whether they prefer to use bash or a different scripting language such as perl, ruby, or python.

Keep Coming For More

--

--

FreakyDodo
FreakyDodo

Written by FreakyDodo

Hey Hackers !! I am Harshit Dodia aka Freaky Dodo , I am a student of Information Technology and Ethical hacking.

No responses yet