Showing posts with label shells script. Show all posts
Showing posts with label shells script. Show all posts

Tuesday, 28 March 2017

Useful Linux Commands - Part 01

1. Command to grep a process and kill

We can use xargs as following. Consider we have a process sleep.sh
 ps -ef  | grep sleep.sh | awk  '{print$2}' | xargs kill -9
 ps -ef  | grep sleep.sh | grep -v 'grep' | awk  '{print$2}' | xargs kill -9


2. Command to list top 10 large sized file in /var directory

sudo du -a /var | sort -n -r | head -n 10

3. Consider demo.csv file with following content.
mukesh@ubuntu:~/Desktop$ cat demo.csv
sno,Item,cost
1,Tea,20
2,Burger,25
3,Ice cream,30
4,Candy,15

Problem 01: Write a command to iterate all the items available in demo.csv file.

cat demo.csv | awk -F ',' '{print $2}' | grep -nv [0-9]
1:Item
2:Tea
3:Burger
4:Ice cream
5:Candy

Problem 02 : Write command to sum up the the cost of items in demo.csv

$ awk -F ',' '{s+=$3}END{print s}' demo.csv
awk -F ',' '{total = total + $3}END{print "Total Amount collected = "total}' demo.csv
Total Amount collected = 90

4. Write a for loop from 1 to 5 in single command

Syntax : for i in {1..5}; do COMMAND-HERE; done
$ for i in {1..5}; do echo $1; done
1
2
3
4
5

5. Write command to all the files in /home/mukesh/Desktop directory.

$ for i in /home/mukesh/Desktop/* ; do echo "$i"; done

6. Write command to grep 2 more lines after the pattern match

$ grep -A2 Tea demo.csv
1,Tea,20
2,Burger,25
3,Ice cream,30

7. Write command to grep 2 more lines before the pattern match

$ grep -B2 Ice demo.csv
1,Tea,20
2,Burger,25
3,Ice cream,30

8. Command to print date 1 day before and and after in YYYY-MM-DD format

refdate=`date +"%Y-%m-%d"`
1 day before date:
refdate=`date --date="1 day before" +%Y-%m-%d`

$ date --date="1 days ago"
$ date --date="1 day ago"
$ date --date="yesterday"
$ date --date="-1 day"

$ date --date="next day"

9. Command to sed the multiple patterns

 sed 's/ab/~~/g; s/bc/ab/g; s/~~/bc/g' file.txt > file_tmp.txt

10. list all files which were created in last 1 Hrs

find <search_dirname> -cmin -60 # creation time
find <search_dirname> -mmin -60 # modification time
find <search_dirname> -amin -60 # access time

11. Command to find all files modified,accessed and permission changed on the 7th of June, 2007:


$ find . -type f -newermt 2007-06-07 ! -newermt 2007-06-08
$ find . -type f -newerat 2008-09-29 ! -newerat 2008-09-30
$ find . -type f -newerct 2008-09-29 ! -newerct 2008-09-30

12. find the files which were created on more/less than 30 days and created exact on 30th day ago

we can use -ctime option with find command as following
    More than 30 days ago: -ctime +30
    Less than 30 days ago: -ctime -30
    Exactly 30 days ago: -ctime 30

13. Command to grep multiple pattern

grep  -e '2015-12-02' -e '2015-12-03' dateFile.txt
grep  '2015-12-02\|2015-12-03' dateFile.txt

14. Command to display cpu info of your linux/Unix system

 Following command will list number of processor on the server and its details.
 cat /proc/cpuinfo

15. How to list top memory consuming process.

 Top + Press Shift  m

16. Command to check linux version

Note : CentOS is based on Redhat Enterprise Linux, while Ubuntu/Ubuntu Server has its roots in Debian
# For ubuntu
 cat /etc/os-release

    root@ubuntu:/etc/ansible# cat /etc/os-release
    NAME="Ubuntu"
    VERSION="12.04.5 LTS, Precise Pangolin"
    ID=ubuntu
    ID_LIKE=debian
    PRETTY_NAME="Ubuntu precise (12.04.5 LTS)"
    VERSION_ID="12.04"

# For centos
 cat /etc/system-release
 cat /etc/redhat-release
  CentOS release 6.5 (Final)




Sunday, 25 December 2016

Array in Linux/Unix Shell Scripting

In Linux shell an Array is the collection of same or different kind of elements which are accessible using zero-based index. In shells array there is no specific data type that means while declaring a shells array no need to define the data type for array. You can store integer, float, string etc in a same array.

This post is part of the shell scripts posts. You can read more basic shell script examples on this page ( http://coolstuffsite.blogspot.in/p/shells-script.html )

In this post i will make shells array easy for you with proper examples.

Declaring a Shell Arrays
To declare a shell array use the following syntax.
declare -a array_name

where array_name is the name of array
Note: In bash, declaring array is not necessary. We can insert element individually with array index.

Declaring and Assigning values to an Array:
Method 01:
Use the following syntax to declare and assigning or initializing the values.
array_name[index]=value

where array_name is the name of array.
      index is position of element which start from zero.
      value is the array value at particular index.
     
Method 02:
You can use another method to declare bash array as following syntax.
array_name=(value1 value2 ... valuen)

This method is useful when you need to take dynamic elements . In this method you can declare space separated static array elements as well as you can place any Linux command, wild cards or SQL query .
For example if we use '*' then it will create a array of all directories and files available in current directory. I will make you understand these concept in following examples .

Accessing Bash Array Elements:
To read the array element use the following syntax.
echo ${array_name[index]}

To access all the array elements use the following syntax.
echo ${array_name[@]}
        #or
echo ${array_name[*]}

To print the number of elements of an array use the following syntax.
echo ${#array_name[@]}

Now lets start some practice with examples.

Example01 : Declaring array with method 01 and accessing array elements.
#!/bin/bash


# Declaring an array demoArray.
declare -a demoArray # It is optional


# Assigning diffrent data type elements to array demoArray
demoArray[0]='Unix'
demoArray[1]='Linux'
demoArray[2]=100
demoArray[4]=50.0
demoArray[5]='"This is demoArray script"'


# Printing third element which is an integer
echo "3rd elemets of array demoArray is : ${demoArray[2]}"
# Printing last element which is a string
echo "6th or last element of array is : ${demoArray[5]}"
# To print all the elements of the array
echo "List of all elemets : ${demoArray[@]}"


# To print the number of elements in the array
echo "Number of elements in array is : ${#demoArray[*]}"


Output:
./bashArray01.sh

3rd elemets of array demoArray is : 100
6th or last element of array is : "This is demoArray script"
List of all elemets : Unix Linux 100 50.0 "This is demoArray script"
Number of elements in array is : 5


Example02: Declaring array with method 02 and accessing array elements.
In the below example 'declare -a demoArray=(Unix Linux 100 50.0 "This is demoArray script")' and 'demoArray=(Unix Linux 100 50.0 "This is demoArray script")' represents the same array.

#!/bin/bash


# Declaring array and assigning static elements
declare -a demoArray=(Unix Linux 100 50.0 "This is demoArray script")


# Printing third element which is an integer
echo "3rd elements of array demoArray is : ${demoArray[2]}"
# Printing last element which is a string
echo "6th or last element of array is : ${demoArray[5]}"
# To print all the elements of the array
echo "List of all elements : ${demoArray[@]}"


# Declaring and initializing array current directory contents.
#declare -a currDirContent=(*)
currDirContent=(*)


# Printing all elements of current directory.
echo "-------------------------------"
echo "Current dir files are : ${currDirContent[@]}"


# Declaring lower case alphabets array
lowercase=({a..z})
# Printing a to z
echo "-------------------------------"
echo "${lowercase[@]}"
Output:
./bashArray02.sh

3rd elements of array demoArray is : 100
6th or last element of array is :
List of all elements : Unix Linux 100 50.0 This is demoArray script
-------------------------------
Current dir files are : bashArray01.sh bashArray02.sh
-------------------------------
a b c d e f g h i j k l m n o p q r s t u v w x y z



Example02: In this example we are creating an array of all emailIds which are in the customer table of a mysql database. To understand this example consider a table "customer" which having the following details.
mysql> select * from customer;
+------------+--------------+----------------------+-----------+
| customerid | customername | emailid              | accountno |
+------------+--------------+----------------------+-----------+
| 1001       | Neeraj singh | neeraj@gmail.com     |     30004 |
| 1002       | Tanu         | tanu@gmail.com       |     30005 |
| 1003       | Shivam Kumar | shivam@yahoo.com     |     30006 |
| 1004       | vinay        | vinay.s@gmail.com    |     30007 |
| 1005       | Ajay singh   | ajay.singh@gmail.com |     30008 |
+------------+--------------+----------------------+-----------+


Once we get array of above emailIds we will access the emails using a for loop.

#!/bin/bash


# Creating array of emails from database. 
declare -a EMAILIDS=(`mysql -umukesh -p*** -hlocalhost -e "SELECT emailid FROM mydb.customer"`)
# The above command will be equivalent to :
# EMAILIDS=(neeraj@gmail.com tanu@gmail.com shivam@yahoo.com vinay.s@gmail.com ajay.singh@gmail.com )


# Accessing emails using for loop
for email in "${EMAILIDS[@]}"
do
    echo "$email"
done


# Print all array of emails
echo "-----------------------------"
echo ${EMAILIDS[@]}


# Printing number of emails
echo "-----------------------------"
echo "Total emails are : ${#EMAILIDS[@]}"

Output:
./bashArray03.sh

neeraj@gmail.com
tanu@gmail.com
shivam@yahoo.com
vinay.s@gmail.com
ajay.singh@gmail.com
-----------------------------
neeraj@gmail.com tanu@gmail.com shivam@yahoo.com vinay.s@gmail.com ajay.singh@gmail.com
-----------------------------
Total emails are : 5

Friday, 24 June 2016

Shell Script To Read a Text File Line by Line

Here i am going to show you two methods of reading a text file with shell script. For our entire exercise consider a demo.txt file which having the following contents .

mukesh@ubuntu:~/Desktop$ cat demo.txt
this is line one
Hello everyone\\ how are you.
this is\ line third with back slash.
This is sample last line.


Method 01: cat file then read line

#! /bin/bash

# Script name : readFile.sh
# Description : Script will read demo.txt which is in current directory.

cat demo.txt | while read LINE
do
        echo $LINE
done


Output:
this is line one
Hello everyone\ how are you.
this is line third with back slash.
This is sample last line.



Method2: Redirecting file into while loop and then read line.

#! /bin/bash

# Script name : readFile.sh
# Description : Script will read demo.txt which is in current directory.

while read LINE
do
    #do what you want to $LINE
    echo $LINE
done < demo.txt

Output:
this is line one
Hello everyone\ how are you.
this is line third with back slash.
This is sample last line.


Note:
If you observe above both the program you will notice in the output back slash "\" is in not printing.
This is happening because program treating "\" as a special character. To avoid this problem use -r while reading line as in the following script.

#!/bin/bash
# Script name : readFile.sh
# Description : Script reading the demo.txt file line by line and treating backslash as a normal character.


if [ $# -ne 1 ]
then
    echo "Usage : $0 filename "
    echo "Give the file name as command line argument."
    echo "Ex.: $0 demo.txt"
    exit 1
fi

filename="$1"

while read -r LINE
do
    echo "$LINE"
done < "$filename"


Output:
this is line one
Hello everyone\\ how are you.
this is\ line third with back slash.
This is sample last line.


where :
-r  Do not treat a backslash character in any special way.
    Consider each backslash to be part of the input line.
   

Shell Script Programs For Beginners - SET 02 ( Case and Loop )

1). Switch case Example 01
2). Switch case Example 02
3). Switch case Example 03
4). For loop Example01 : Simple for loop.
5). For Loop Example02 : List all content of current directory.
6). For loop Example03: Executing unix command in loop.
7). While loop Example 01: simple while loop
8). Until loop Example01: Simple until loop
9). For loop with break keyword
10). For loop with continue keyword

1) Switch case Example 01

#!/bin/bash
#
#Script Name : caseExample01.sh 
#Description : Script will read a value from user and choose accordingly choice.
#
echo "Enter the number from 1 to 4"

read x

case $x in 
    1) echo "One";;
    2) echo "Two";;
    3) echo "Three";;
    4) echo "Four";;
    *) echo "Wrong input, Please enter number 1 to 4";;
esac

Output:
Case 1 : if x=2
Two
Case 2 : if x=4
Four
Case 3 : if x=0 or 5 or 10 or d
Wrong input, Please enter number 1 to 4


2) Switch case Example02
#!/bin/bash
#
#Script Name : caseExample02.sh 
#Description : Script will read a value from user and choose accordingly choice.
#               Keeping default '*)' in between rather keeping it at end and observe the output of program.
#

echo "Enter the number from 1 to 4"
read x
case $x in 
    1) echo "One";;
    2) echo "Two";;
    3) echo "Three";;
    *) echo "Wrong input, Please enter number 1 to 4";;
    4) echo "Four";;
esac

Output:
Case 1 : if x=1
One
Case 2 : if x=4
Wrong input, Please enter number 1 to 4
Case 3 : if x=0 or 5 or 10 or d
Wrong input, Please enter number 1 to 4


If you observe the above program it is clear that the case which are places after default case those does not come under consideration of program.

3) Switch case Example 03
#!/bin/bash
#
#Script Name : caseExample03.sh 
#Description : Script will read a value from user and choose accordingly choice.
#               We can use expression also in case.
#

case `expr 20 + 5` in 
    10) echo "Ten";;
    25) echo "Twenty Five";;
    30) echo "Thirty";;
    *) echo "Wrong input";;
esac

Output:
Twenty Five

Loop:
Loops are very powerful tool to perform a set of instructions repeatedly until a certain condition is reached.
For,While and Until are the popular loop in shell program . Following are the example of each kind of loops.

4) For loop Example01 : Simple for loop
#!/bin/bash
#
#Script Name : for01.sh
#Description : Script showing demo of a simple for loop
#

for val in a b c d e f g h i j
do
        echo $val
done


5) For Loop Example02 : List all content of current directory
#!/bin/sh
#
#Script Name : for02.sh
#Description : Script showing demo of a for loop in which program listing all the contents of current directory.

for val in *
do
  echo "$val"
done

Remember * is Wildcard which will consider all the contents of current directory hence the above program will loop all the file and directory available in current directory.

6) For loop Example03: Executing unix command in loop
#!/bin/sh
#
#Script Name : for03.sh
#Description : Script showing demo of a for loop in which program is executing unix commands

for val in date cal exit who

do
   "$val"
done

Output:
Mon Dec 12 22:05:57 IST 2016
   December 2016
Su Mo Tu We Th Fr Sa
             1  2  3
 4  5  6  7  8  9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31

Note : Replcae "$val" to echo "$val" in above program and observe the output.


While Loop:

In 'while' loop, we give one control command to control the iteration of the loop
A set of commands will be executed as long as the control command's exit status is 0
When the control command's exit status becomes 1, the 'while' loop is quit.

7) While loop Example 01: simple while loop
#!/bin/sh
#
#Script Name : while01.sh
#Description : A simple while loop demo

a=0

while [ $a -lt 10 ]
do
   echo -ne "$a\t"
   a=`expr $a + 1`
done


Output:
0       1       2       3       4       5       6       7       8       9

Note : In above program i used -n and -e option where -n option is used to disable trailing new line character.
and -e option is used to enable escape sequences and \t is used for tab.

Until loop:
A until loop is used to repeat set of commands as long as the control command's exit status is 1
When the control command's exit status becomes 0, the loop is get quit.

8) Until loop Example01: Simple until loop
#!/bin/sh
#
#Script Name : until01.sh
#Description : A simple until loop demo


echo  "Type 'end' to exit  "
read var
until  [  "$var"  =  "end"  ]
do
    `echo $var`
     read  var
done

echo  "End of the script and exiting"


Output:
Type 'end' to exit
date
Mon Dec 12 23:13:00 IST 2016
end
End of the script and exiting


Break and Continue Keywords:
In shell scripts we can use break and continue keywords only in the looping statements (i.e., while , until and for).

9) For loop with break keyword
In the following example as soon variable i become equal to 5 the loop breaks and quit.
#!/bin/sh
#
#Script Name : break.sh
#Description : A simple break keyword in a loop


for i in 1 2 3 4 5 6 7 8
do
    echo $i
    if [ $i -eq 5 ]
    then
        break
    fi

done

Output:
1 2 3 4 5

10) For loop with <b>continue</b> keyword
Following example showing the a demo of 'continue' keyword in which it print which are not equal to 5, as soon controller reach to 5 continue keyword move it to the next number.

#!/bin/sh
#
#Script Name : continue.sh
#Description : A simple continue keyword in a loop

for i in 1 2 3 4 5 6 7 8

do
#   echo $i
    if [ $i -ne 5 ]
    then
        echo $i
    else
        continue
    fi

done


Output:
1 2 3 4 6 7 8

Tuesday, 24 May 2016

Unix System Architecture

There 4 major components in the Unix system.

Kernal : Monitors and controls the resources of a computer and allocates them among its users in an
              optimal manner.
Shell    : Provides a processing environment for the user programs and acts like a command translator
Utilities : Programs which are used for development purposes
User Applications : Programs written by the user

The above 4 components can be understood better by a layer approach as following:





Layer 1 (Hardware ) : 

This layer is the hardware over which the different OS layers are built. Hardware is not a part of the Unix OS.

Layer 2 (Kernal) :

This layer is the Kernel, which is the most important component of the Unix system. It is a collection of programs which directly communicate with the hardware. It is that part of the Unix system that is loaded into memory first when the system is booted. It manages the system resources, allocates them between users and the processes, decides priorities of different processes etc.

Layer 3 (User Application/Commands): 

This layer contains programs that interact with the Kernel by invoking some system-calls. Basically these programs are Unix commands like wc, grep, find etc.

Layer 4 (Shell):

This layer is called Shell. Technically another Unix command, it is the interpreter of user requests. It takes a command from the user, deciphers it, and communicates with the Kernel to see that the command is executed. It is actually the interface between the user and the kernel, which effectively insulates the user from the knowledge of kernel functions. It also has a programming capability of its own.

The kernel and shell together make the Unix system work. The shell provides a processing environment to the user programs.




Monday, 14 March 2016

Unix/Linux Shell Variables

Variables in Unix/Linux Shell

To process our data/information, data must be kept in computers RAM memory. RAM memory is divided into small locations, and each location had unique number called memory location/address, which is used to hold our data. Programmer can give a unique name to this memory location/address called memory variable or variable (Its a named storage location that may take different values, but only one at a time).

In Unix/Linux(Shell), there are two types of variable:

1)  System variables : 

    Created and maintained by Linux itself. This type of variable defined in CAPITAL LETTERS.
    You can see system variables by giving command like $ set, There is a long list of system variable
    so if you interested to see all the system variable then you should redirect the all system variable
    into a text file by using command as "set > systemVariable.txt". Now check systemVariable.txt in
    your current directory.

Some of the important System variables are as following:
   
System Variable Description
BASH=/bin/bash System Shell Name
BASH_VERSION=4.2.25(1)-release System Shell Version Name
COLUMNS=80 Number of Column for your screen
LINES=34 Number of Lines for your screen
HOME=/home/mukesh Your Shell's Home Directory
LOGNAME=mukesh Logging Name of Current System
OSTYPE=Linux Our Operating System Type
PATH=/usr/bin:/sbin:/bin:/usr/sbin Our System's Path Setting
PS1=[\u@\h \W]\$ Our Prompt Settings
SHELL=/bin/bash Our Shell Name
PWD=/home/mukesh/Documents Our Current Working Directory
USERNAME=mukesh Username who is currently log in into system
   
   
    Note :Some of the above settings can be different in your Unix/Linux environment as per your system.
    You can print any of the above variables contains as follows:

    $ echo $USERNAME
    $ echo $BASH_VERSION



2) User defined variables : 
  •   Created and maintained by user. This type of variable defined in lower letters.
  •   User-defined variable can be assigned a value.
  •   The value of a named variable can be retrieved by preceding the variable name with a ‘$’ sign
  •   Used extensively in shell-scripts.
  •   Used for reading data, storing and displaying it.

    Accepting Data and Displaying It on Screen:

  •  To accept input data from user you can use read command.
  •  In shell scripts , read is used for accepting data from the user and storing it for other processing.
  •  Example : $ read yourname

  • Type command "read yourname" and hit enter. Type your name and hit enter again. So now your name has been stored into user defined varaible name yourname.

    Displaying Value:
    To display the value you can use the echo command.
    So to display your name which you have stored into a variable yourname type the following command.

      echo $yourname



Wednesday, 9 March 2016

Shell Script Programs For Beginners - SET 01

1). Writing your first script and getting it to work .
2). Script which shows a demo of command line arguments.
3). Script to print user login information with current date and time.
4). To read input from user and showing demo of user defined variable.
5). Script to show an example of user defined variable.
6). Script to sum 2 numbers given by user.
7). Script to show sum of numbers with decimal points
8). Script to find the biggest no from the 3 numbers
9). Script to print 1 to 10 numbers using while loop
10). Script to show a demo of for loop

1). Writing your first script and getting it to work .

Step 1 : writing the script
You can write script either on note pad or by using vi editor.Let us use vi editor. Open your Linux terminal and create a file helloWorld.sh for this type "vi helloWorld.sh" and hit enter . Now hit ' i ' to go in insert mode and write the following code in your file.
#!/bin/bash
#
# Script name : helloWorld.sh

echo "Hello world !"
To save helloWorld.sh first hit 'esc' to come out from insert mode and then type ':wq!' and hit enter. Now type 'ls' command to see your file.

Step 2 : Give the execute permission to the file helloWorld.sh ,run the following command
mukesh@ubuntu:~$ chmod 755 helloWorld.sh 
            (or)
mukesh@ubuntu:~$ chmod +x helloWorld.sh 
Step 3 : Run the helloWorld.sh
mukesh@ubuntu:~$ ./helloWorld.sh
Hello world !
             (or)
mukesh@ubuntu:~$ sh helloWorld.sh 
Hello world !
2).Script which shows a demo of command line arguments.
#!/bin/bash
#
#Script Name : commandLineArgument.sh
#Description : The Script will show ,command line argument demo
#
clear
if [ $# -le 0 ]
then
        echo "usage :- $0 arg1 arg2 arg3 ...argN"
        echo "where arg1,arg2...argN are command line argument"
else
        echo "Total no of command line argument are $#"
        echo "$0 is the Script Name"
        echo "$1 is the first argument"
        echo "$2 is the second argument"
        echo "all of them are $* or $@"
fi
3).Script to print user login information with current date and time.
#!/bin/bash
#
#Script name : userLoginDEtail.sh
#Author      : mukesh kumar
#Description : Script to print user information who currently login ,current date & time
#
echo "Hello, $LOGNAME"
echo "Current date is `date`"
echo "User is `who i am`"
echo "Current direcotry is `pwd`"
echo "==========Another way==========="
clear
echo "Hello $USER"
echo -e "Today is \c ";date
echo -e "Number of user login :\c ";who | wc -l
echo "Calendar"
cal
exit 0 
4).To read input from user and showing demo of user defined variable.
#!/bin/bash
#
#Script Name : readUserInputandUDV.sh
#Description : To read input from user and showing demo of user defined variable.
#
clear
echo  "Please ! Enter your Name :"
read Name
echo "hello $Name ,How are you ?"
myname=Mukesh
myos=linux
echo "My name is $myname and my operating system is $myos"
5).Script to show an example of user defined variable.
#!/bin/bash
#
#Script Name : userDefinedVariable.sh
#Description : Script to demonstrate the UDV.
#
myname=Mukesh
myos=linux
nyno=242100
echo "My Name is $myname"
echo my os is $myos"
echo "My number is myno, can u see this number ?"
6).Script to show sum of two numbers.
#!/bin/bash
#
#Script Name : sumofNumber.sh
#Description : Script to sum of two numbers.
#
clear
if [ $# -ne 2 ]
then
        echo "usage - $0 x y"
        echo "          where x and y are 2 numbers"
        exit 1
else
        echo "sum of $1 and $2 is `expr $1 + $2`"
        exit 0
fi
7). Script to show sum of numbers with decimal points.
#!/bin/bash
#
#Script Name : sumDecimalPoint.sh
#Description : Script to show sum of numbers with decimal points
#

if [ $# -ne 2 ]
then
        echo "Usage : $0 num1 num2 "
        echo "give 2 nos with argument with decimal point,i will sum then"
        exit 1
fi
n1=$1
n2=$2
sum=0
sum=`echo $n1 + $n2 | bc`
echo "sum of $n1 + $n2 = $sum"
8). Script to find the biggest no from the 3 numbers.
#!/bin/bash
#
# Script Name : biggestNumber.sh
# Description : Script to find the biggest no from the 3 numbers
#
if [ $# -ne 3 ]
then
        echo "Usage - $0 n1 n2 n3"
        echo "          where n1 ,n2 and n3 are number among which biggest no has to find"
        exit 1
fi
n1=$1
n2=$2
n3=$3

if [ $n1 -gt $n2 ] && [ $n1 -gt $n3 ]
then
        echo "$n1 is the biggest number"

elif [ $n2 -gt $n1 ] && [ $n2 -gt $n3 ]
then
        echo "$n2 is the biggest number"

elif [ $n3 -gt $n1 ] && [ $n3 -gt $n2 ]
then
        echo "$n3 is the biggest number"

elif [ $n1 -eq $n2 ] && [ $n1 -eq $n3 ] && [ $n2 -eq $n3 ]
then
        echo "all numbers are equal"
else
        echo "I couldn't figure out which number is gretest"
fi
9). Script to print 1 to 10 numbers using while loop.
#!/bin/bash
#
#Script Name : whileLoop.sh 
#Description : while loop to print 1 to 10 numbers.
#

i=1
while [ $i -le 10 ]
do
        echo "$i"
        i=`expr $i + 1`
done
10). Script to show a demo of for loop.
#!/bin/bash
#
#Script Name : forLoop.sh
#Description : Script showing demo of for loop
#

for val in a b c d e f g h i j
do
        echo $val
done

Tuesday, 8 March 2016

Nagios Plugin to check used space

Here is very simple Nagios plugin in shells script which can be be used to check the used disc space in server and accordingly can be get alert mail.

  • If used space less than 70%, then output status remains "OK"
  • if used space >=70% and < 90%, then output status will be "WARNING"
  • If used space >=90%, then output status will be "CRITICAL"
  • If none of the above, then output status will be "Unknown" 

Following is the script for the above requirements :
#!/bin/bash

# Script Name : usedSpace.sh
# Description : This script will check total used space in % of current disc .


used_space=`df -h / | grep -v Filesystem | awk '{print $5}' | sed 's/%//g'`

case "$used_space" in
        [1-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]|6[0-9])
                echo "OK - $used_space% of disk space used."
                exit 0
                ;;
        7[0-9]|8[0-9])
                echo "WARNING - $used_space% of disk space used."
                exit 1
                ;;
        9[0-9]|100)
                echo "CRITICAL - $used_space% of disk space used."
                exit 2
                ;;
        *)
                echo "UNKNOWN - $used_space% of disk space used."
                exit 3
                ;;
esac


You can change script as per your used space percentage and can set the email alerting if it is in "WARNING", "CRITICAL" or "UNKNOWN" state.


Tuesday, 23 February 2016

The VI Editor

The vi editor (stands for visual editor) is a screen editor which is available on almost all Unix systems. Once you have learned vi, you will find that it is a fast and powerful editor. There is also a improved version of VI called VIM.

Vi editor works on different UNIX flavors. It is fast and powerful undo features. There are few limitations also there it is less user friendly, high case sensitive and keystroke could have more than one meanings.

Working modes of VI editor :

Command Mode : Keys are interpreted as commands.
Insert Mode         : Keys are interpreted as data
Escape Mode       : Keys are interpreted for saving/exiting purposes





Whenever a particular file is opened using the vi editor, it opens up in the Command mode. In this mode, the keyboard-character represents command and not data. A user cannot enter the data in the Command mode. The user has to switch over to the insert mode to enter the data. This could be done using the letters like "a", "i", etc. Once the user is in insert mode, the data could be entered. The user could switch back to the Command mode. For saving or exiting the application the user has to get into the Escape mode by pressing "Esc" key.

General Startup
 
    To use vi: [vi filename] + Enter
    To exit vi and save changes:    Esc Key+[ ZZ   or  :wq ] + Enter
    To exit vi without saving changes:    [ Esc Key + :q! ] + Enter
    To enter vi command mode:    [Esc]

Cursor Movement

 
    h       move left (backspace)
    j       move down
    k       move up
    l       move right (space-bar)


    [return]   move to the beginning of the next line

    $       last column on the current line
    0       move cursor to the first column on the current line
    ^       move cursor to first non blank column on the current line
    w      move to the beginning of the next word or  punctuation mark
    W     move past the next space
    b       move to the beginning of the previous word  or punctuation mark
    B      move to the beginning of the previous word, ignores punctuation

        e       end of next word or punctuation mark
        E      end of next word, ignoring punctuation
        H      move cursor to the top of the screen
        M      move cursor to the middle of the screen
        L       move cursor to the bottom of the screen

Screen Movement
 
       G        move to the last line in the file
       gg        move to the first line in the file
       xG       move to line x


       z+       move current line to top of screen
       z        move current line to the middle of screen
       z-       move current line to the bottom of screen

       ^F       move forward one screen
       ^B       move backward one line

       ^D       move forward one half screen
       ^U       move backward one half screen

Inserting
 
       i        insert before cursor
       a        append after cursor

       A        append at end of line
       O        open line above cursor and enter append mode
       r        replace character under cursor with next character typed
       R        keep replacing character until [esc] is hit

Deleting
 
    x       delete character under cursor
    dd      delete line under cursor

    dw      delete word under cursor
    db      delete word before cursor

Copying Code
 
    yy      (yank)'copies' line which may then be put by the p(put) command. Precede with a count
              for multiple lines.

Put Command
 
        Brings back previous deletion or yank of lines,words, or characters
        P       bring back before cursor
        p       bring back after cursor

 Find Commands
 
    ?       finds a word going backwards
    /       finds a word going forwards


    f       finds a character on the line under the cursor going forward
    F       finds a character on the line under the cursor going backwards

    t       find a character on the current line going forward and stop one character before it
    T       find a character on the current line going backward and stop one character before it

    ;        repeat last f, F, t, T

Miscellaneous Commands
 
    ^G    display current line number
    .        repeat last command
    u       undoes last command issued
    U      undoes all commands on one line

Line Editor Mode
    Any commands form the line editor ex can be issued upon entering line mode.

    To enter: type ':'
    To exit: press[return] or [esc]

READING FILES
    copies (reads) filename after cursor in file currently editing

    :r filename

WRITE FILE
    :w     saves the current file without quitting

MOVING
    :#    move to line #
    :$    move to last line of file

SHELL ESCAPE
    executes 'cmd' as a shell command.
    :!'cmd'






                         **********************END************************
Related Posts Plugin for WordPress, Blogger...