Introduction to Linux - A Hands on Guide | Linux Bible | Linux From Scratch | A Newbie's Getting Started Guide to Linux | Linux Command Line Cheat Sheet | More Linux eBooks



Tuesday, 3 September 2013

Basic Linux Shell Scripting Language - Creating Shell Scripts

In the previous article on Linux Shell Scripting Language, we had already covered following points:

  • What is a Shell?
  • Types of Linux Shell- Bourne Shell, C Shell, Korn Shell and the BASH Shell (Bourne Again Shell).
  • Shell Programming - The Basics
  • Writing the First Shell Script - Hello World


 In this article, we would write some more basic shell scripts that will give you much more comfort while writing more complex scripts. Please note that, this article is an extension of my previous article "Getting Started - Linux Shell Scripting Language".
So, without much a do, lets start the show.

1. Fun with the $USER

In the first script of this article, we will make use of the shell variable $USER. It stores the information about active user of the system. Just observe the following script that displays IP Address Details to its user.

Code:

#!/bin/bash
echo "Hello $USER"
echo "Hey ${USER}, Let me show you your IP Address Details -"
echo "______________________________________________"
echo "IP Address Details"
ifconfig
Output:

Hello root !
Hey root, Let me show you your IP Address Details -
___________________________________________________
IP Address Details:

eth0      Link encap:Ethernet  HWaddr 08:00:27:A1:7C:6A
          inet addr:192.168.0.102  Bcast:192.168.0.255  Mask:255.255.255.0
          inet6 addr: fe80::a00:27ff:fea1:7c6a/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:499 errors:0 dropped:0 overruns:0 frame:0
          TX packets:407 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:62821 (61.3 KiB)  TX bytes:63184 (61.7 KiB)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:12 errors:0 dropped:0 overruns:0 frame:0
          TX packets:12 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:720 (720.0 b)  TX bytes:720 (720.0 b)
Remember, whenever you try to create a script, it should have an extension .sh and make it executable before you run it.

Script is nothing but a number of commands pipelined together. Shell Scripts are just great for concise file-system operations. When you need Better functionality,  better robustness, better performance and better efficiency then you may adopt a more full-featured language.

If you are acquainted with programming languages like C or Python or Perl, then you can learn Shell Scripting with much more comfort.

2. An Interactive Script

    In the second script of this article, we expect the user to take part in the communication. This script will take texts from the user, save it in some variables and using those variables, something is displayed back on the screen for the user.

Code:

#!/bin/bash
echo -e "Please enter your First name:\n"
read FName
echo -e "Please enter your Last name:\n"
read LName
echo "Welcome, ${FName} ${LName}!"
Code:

Please enter your First name:
Mandar
Please enter your Last name:
Shinde
Welcome, Mandar Shinde!

3. Build a Pyramid of Stars

    Most of us might have done this program in C language. In the similar fashion, using for loops, we can display a pyramid of stars (*s) using Shell scripts. Go through the program and you will find the commands self explanatory. In case you find any difficulties, please refer to the articles on Conditional statements and For loops.

Code:

#!/bin/bash
LINES=0
echo -n "Enter the number of Lines (5 to 10): "
read LINES

if ![ $LINES -ge 5 -a $LINES -le 10 ]
then
 echo "Error: Number is not between 5 and 10. Try again."
 exit 1
fi
clear
for (( i=1; i<=LINES; i++ ))
do
 for (( j=LINES; j>=i; j-- ))
 do
  echo -n " "
 done
 for (( k=1; k<=i; k++ ))
 do
  echo -n " *"
 done
 echo ""
done
Output:

MyLinuxBox root /user/Test > ./pyramid.sh
Enter the number of Lines (5 to 10): 8
         *
        * *
       * * *
      * * * *
     * * * * *
    * * * * * *
   * * * * * * *
  * * * * * * * *

4. Make It Colorful

   Shell scripts commonly used ANSI escape codes for color output. Following table shows Numbers representing colors in Escape Sequences.


To make use of these colors in your scripting, use following syntax:
echo -e "\033[<code>m <Your Text>"
For Example,
echo -e "\033[32m Your Own Linux...!"

    Not only this, but you can make your text more fancy by giving them some text attributes. The following table summarizes numbers representing text attributes in Escape Sequences.



Code:

#!/bin/bash
echo -e "\033[1m I am Bold\e[0m"                # BOLD EFFECT
echo -e "\033[5m I am Blinking\e[0m"            # BLINKING EFFECT
echo -e "\033[0m I am Normal\e[0m"              # NORMAL TEXT

echo -e "\033[31m I am Red\e[0m"                # RED FOREGROUND
echo -e "\033[32m I am Green\e[0m"              # GREEN FOREGROUND
echo -e "\033[33m I am Yellow\e[0m"             # YELLOW FOREGROUND
echo -e "\033[34m I am Blue\e[0m"               # BLUE FOREGROUND
echo -e "\033[35m I am Magenta\e[0m"            # MAGENTA FOREGROUND
echo -e "\033[36m I am Cyan\e[0m"               # CYAN FOREGROUND

echo -e "\033[0m I am Normal again..\e[0m"      # NORMAL TEXT

echo -e "\033[41m I am Red\e[0m"                # RED BACKGROUND
echo -e "\033[42m I am Green\e[0m"              # GREEN BACKGROUND
echo -e "\033[43m I am Yellow\e[0m"             # YELLOW BACKGROUND
echo -e "\033[44m I am Blue\e[0m"               # BLUE BACKGROUND
echo -e "\033[45m I am Magenta\e[0m"            # MAGENTA BACKGROUND
echo -e "\033[46m I am Cyan\e[0m"               # CYAN BACKGROUND

echo -e "\033[0m I am Normal yet again..\e[0m"  # NORMAL TEXT
Output:


5. Compress a File/Folder

Let us now create a script that will compress a file/directory specified by the user. This is yet another interactive script which will ask the user to input the exact file/directory name (along with extension if any), compress it and output a compresses version of the same with the name 'archive.tar.gz'.

Code:

#!/bin/bash
echo "Welcome $USER !"
echo "Let me compress a file for you."
echo "Enter the directory name where the target file is kept"
read DIR
echo "Enter the file name you wish to compress -"
read FILE
cd $DIR
tar -cvzf archive.tar.gz 
echo "File $FILE successfully compressed as archive.tar.gz"
Output:

Welcome root !
Let me compress a file for you.
Enter the directory name where the target file is kept
/user/Test
Enter the file name you wish to compress -
testfile.txt
testfile.txt
File testfile.txt successfully compressed as archive.tar.gz

6. Email Alert!

Time to create a script that will send you an email when disk utilization exceeds some pre-determined threshold. If you are a system administrator, then this script will prove to be pretty essential for you. Check out the script:

#!/bin/bash

THRESHOLD=90
RCPT=Username@Domain.com
PARTITION=sda1
USAGE=`df -h | grep $PARTITION | awk '{print $5}' | tr -d '%'`

if [ $USAGE -gt $THRESHOLD ]
then
 echo "$PARTITION Disk Usage = ${USAGE}%" | mail -s "Running out of space" $RCPT
fi
    You need to make a few changes in the script, replace the field 'Username@Domain.com' with your Email ID and it's done.

    That's all for this article! There are no boundaries when it comes to writing scripts and programming stuffs, you can create as many scripts as you want. If you like this article or you have some suggestions, fell free to comment and stay tuned for some more articles on Linux Shell Scripting Language. Happy Scripting!


0 comments:

Post a Comment

    Total Pageviews