Shell script to email CPU and MEMORY usage

DESCRIPTION:
Install sysstat and postfix before running the script

SCRIPT:

#!/bin/bash
#install below packeges befor running the script
#sudo apt-get install sysstat, sudo apt-get install postfix
SUB_CPU="CPU USAGE"
SUB_MEMORY="MEMORY USAGE"
TO=youradmin@anymail.com
CPU_LOG=/var/log/mylog
MEMORY_LOG=/tmp/mem_log
while ((1))
do
mpstat > $CPU_LOG
mail -s "$SUB_CPU" "$TO" < $CPU_LOG
sleep 2
cat $CPU_LOG
egrep --color 'Mem|Cache|Swap' /proc/meminfo > $MEMORY_LOG
mail -s "$SUB_MEMORY" "$TO" < $MEMORY_LOG
sleep 2
cat $MEMORY_LOG
sleep 60
done

OUTPUT:

sujin@sujin:~/sujin/work$ sudo ./test.sh
Linux 3.0.0-24-generic (sujin) 03/22/2013 _i686_ (4 CPU)

06:56:24 PM  CPU    %usr   %nice    %sys %iowait    %irq   %soft  %steal  %guest   %idle

06:56:24 PM  all    6.58    0.01    1.32    0.93    0.00    0.01    0.00    0.00   91.15
MemTotal:        3526272 kB
MemFree:         1495584 kB
Cached:          1072248 kB
SwapCached:            0 kB
SwapTotal:       4098044 kB
SwapFree:        4098044 kB
Linux 3.0.0-24-generic (sujin) 03/22/2013 _i686_ (4 CPU)

06:57:28 PM  CPU    %usr   %nice    %sys %iowait    %irq   %soft  %steal  %guest   %idle

06:57:28 PM  all    6.55    0.01    1.32    0.93    0.00    0.01    0.00    0.00   91.18
MemTotal:        3526272 kB
MemFree:         1508548 kB
Cached:          1054596 kB
SwapCached:            0 kB
SwapTotal:       4098044 kB
SwapFree:        4098044 kB


Shell script to convert string lower to upper and upper to lower

SCRIPT:
#!/bin/bash
echo -n "enter any string in lowercase : "
read l_str
u_str=`echo $l_str | tr [a-z] [A-Z]`
echo "lower to upper converted o/p : $u_str"


echo -n "enter any string in uppercase : "
read u_str
l_str=`echo $u_str | tr [A-Z] [a-z]`
echo "upper to lower converted o/p : $l_str"

OUTPUT:
sujin@sujin:~/work/shell$ bash lwr2upr.sh
enter any string in lowercase : cricket
lower to upper converted o/p : CRICKET
enter any string in uppercase : FOOTBALL
upper to lower converted o/p : football



Shell script to find simple interest

SCRIPT:
#!/bin/bash
echo -n "enter principal : Rs."
read principal
echo -n "enter number of years : "
read year
echo -n "enter rate of interest : "
read interest
simple_interest=`expr "($principal * $year * $interest)/100"|bc`
echo "simple interest = Rs.$simple_interest"

OUTPUT:
sujin@sujin:~/work/shell$ bash SI.sh
enter principal : Rs.2000
enter number of years : 3
enter rate of interest : 8
simple interest = Rs.480
 
 

Shell script to cancatenate two string

SCRIPT:
#!/bin/bash
echo -n "Enter the 1st string : "
read str1
echo -n "Enter the 2nd string : "
read str2
cat_str="$str1$str2"
echo "cancatenated string : $cat_str"

OUTPUT:
sujin@sujin:~/work/shell$ bash str_concatenate.sh
Enter the 1st string : sujin
Enter the 2nd string : sr
cancatenated string : sujinsr
 

Shell script to find string length

SCRIPT:
#!/bin/bash
echo -n "enter the string : "
read str
length=`expr $str|wc -c`
length=`expr $length - 1`
echo "the length of the entered string $str is $length"

OUTPUT:
sujin@sujin:~/work/shell$ bash find_length.sh
enter the string : linux_ubuntu
the length of the entered string linux_ubuntu is 12


Shell script to ping IP

Here you can see the simple and easy way to check your PC able to ping particular IP.

SCRIPT:
#!/bin/bash
ping -c 3 $1 > /dev/null
if [[ $? -eq 0 ]]
then
    echo "ping success"
else
    echo "ping failed"
fi

OUTPUT:
i)
run -> ./ping.sh 192.168.1.4
ping success
 
ii)
run -> ./ping.sh 10.10.62.1 
ping failed
 

shell script to identify input entered or not

SCRIPT:
#!/bin/bash
echo -n "enter any value : "
read val
if [[ -n $val ]]
then
    echo "input entered"
else
    echo "not entered"
fi

OUTPUT:
i)run -> ./enter.sh
enter any value :
not entered
 
ii)run -> ./enter.sh
enter any value : hi
input entered
 

Shell script to check the file and directory availability

SCRIPT:
#!/bin/bash
DIR=/home/sujin/work/
FIL=/home/sujin/work/shell/if.sh

if [[ -d $DIR && ! -L $DIR ]]
then
    echo "directory $DIR available"
else    
    echo "directory $DIR not available"
fi

if [[ -f $FIL && ! -L $FIL ]]
then
    echo "file $FIL available"
else
    echo "file $FIL not available"
fi


OUTPUT:
run -> ./dir_file_avail.sh
directory /home/sujin/work/ available
file /home/sujin/work/shell/if.sh available


Command line argument in shell script

Passing arguments to the main program when it start is know as command line arguments   

In shell scripting arguments can be described like below

$0 - shows program name which you running
$1 - shows first argument 
$2 - display second argument
$3 - display third argument
$n - n th argument
$# - shows number of arguments passed to the program
$* - shows entire string of parameters you passed


Break and Continue statement in shell script

DESCRIPTION:
All statement inside the loop executed as long as some condition are true.

If break placed inside the loop, when loop reach the break statement it will terminated out from the loop.

If continue placed inside the loop, when loop reach the continue statement it will not execute next lines of the loop and it will go to the next iteration.

Function in shell script

DESCRIPTION: 
Function is the piece of code, which executed when we call.
When thinking about the function in any computer language, three points comes in mind

  1. Writing function code and calling that function when we need
  2. Passing arguments to the function
  3. Returning value from function

Next i going to elaborate about the 3 points i mentioned above 

Until loop in shell script

Until loop is opposite to while loop.

It will execute the loop as long as condition false.


When condition meet true it will terminate from the loop.

While loop in shell script

While will execute the loop as long as condition true.

When condition meet false it will terminate from the loop.

For loop in shell script

For loop will execute the loop again and again, until particular condition is true.

Case statement in shell script

Case is used to select one value from multiple option.

It is alternate and easy way to multi level if statement.

Case statement end with 'esac'.

If loop in shell script

if script:
#!/bin/bash
echo -n "enter the key : "
read key
if [ $key -eq 1122 ]
then
   echo "you entered correct key"
fi
output:
enter the key : 1122
you entered correct key


Numeric comparision in shell script

eq - equal:
     var1 -eq var2
     var1 equal to var2

ne - not equal:
     var1 -ne var2
     var1 not equal to var2

gt - greater :
    var1 -gt var2
    var1 greater than var2

Variables in shell script

Variables are use to assign the value of data types such as integer, float, string, etc.   

In shell scripting no need to specify types for your variable.
Create integer variable
     In C language
           int a = 10;
     In shell script
           a=10

First Shell Script In linux



1. Open terminal window in Linux

2. Create a directory for all of you shell script you going to do
              mkdir shell

3. Go to the directory and create a file to  write your script
             cd shell
             vi first.sh

Introduction to shell script

KERNEL:

Kernel act as the mediator between the computer hardware and application.

SHELL:

Shell reads the commands from the user and translate them to understandable by kernel.

SHELL SCRIPT:

Shell script is a file which stores the series of commands. Shell will execute this text file instead of entering the commands.



Display All The Text Files From A Directory Using C

DESCRIPTION:
  • This program get the directory path from the user and display all the text files available in the directory.
  • We should add dirent.h header file to accomplish this program.
  •  
PROGRAM:

#include <string.h>
#include <dirent.h>
#include <string.h>
const char *only_txt (const char *);

int main (int argc, char *argv[])
{
    DIR *directory;
    struct dirent *file;    
    directory = opendir (argv[1]);
    int directory_length = strlen(argv[1]);
    if (directory != NULL){
        while (file = readdir (directory)){
            if( !strcmp((only_txt (file->d_name)), ".txt") )
                      puts (file->d_name);
        }
        (void) closedir (directory);
      }
      else
        perror ("Not able to open the directory\n");
    return 0;
}

/**load only .txt file**/

const char *only_txt (const char *filespec)
{
    char *file = strrchr (filespec, '.');
        if (file == NULL)
            file = "";
    return file;
}

COMPILE:

    gcc -o out scan.c

RUN:
  • Pass the directory name with the path as argument to the program
        ./out /home/sujin/directory

OUTPUT:

      test.txt
   README.txt
      file.txt
 
CONCLUSION:
 
   Changing ".txt" to any type file extension, you can customize this program for file type you like.

 

Shell script to find sum of two numbers

DESCRIPTION:
  • This script will read two integer value from users and give output as sum of two values
SCRIPT:

    #!/bin/bash
   
    echo -n "Enter the first number : "
    read num1
    echo -n "Enter the second number : "
    read num2
    sum=`expr $num1 + $num2`
    echo "sum of two value is $sum"

RUN: 

    sh sum.sh

OUTPUT:

   Enter the first number : 23
   Enter the second number : 45
   sum of two value is 68