Friday, June 17, 2011

Some Scripting Excersises

1.) Using Test Command to find Wether entered Argument is File or Directory.

[root@server2 ~]#cat
test -d $1
ks=`echo $?`
if [ $ks -eq "0" ];  then
 echo $1 is Directory;
 echo "Entered Argument is not Directory"
[root@server2 ~]#
[root@server2 ~]#./ /etc
/etc is Directory
[root@server2 ~]#
[root@server2 ~]#./ /etc/passwd
Entered Argument is not Directory
[root@server2 ~]#

2.) Bash For Loop Example for Unzip all the Zip file

The following example finds the list of files which matches with “*.zip*” in the root directory, and creates a new directory in the same location where the zip file exists, and unzip the zip file content.
# cat
#! /bin/bash
# Find files which has .zip
for file in `find /root -name "*.zip*" -type f`

# Skip the extension .zip
dirname=`echo ${file} | awk -F'.' '{print $1}'`

# Create the directory
mkdir $dirname

# Copy the zip file
cp ${file} ${dirname}
cd $dirname

# Unzip the zip file from newly created directory
unzip ${dirname}/$(echo ${file##/*/})
  • In this example find command returns the list of files, from which each file will be processed through a loop.
  • For each item, it creates the directory with the name of the zip file, and copies the zip file to the newly created directory and unzip the zip file from there.
  • The echo statement, echo ${file##/*/} gives you only the file name not the path.

3.) Processing a File Line by Line using script.

 [root@server199 ~]# cat
# PURPOSE : Proscess a File line by line and read its contents

while read LINE
        let count++
        echo "$count $LINE"
done < $FILENAME

echo -e "\nTotal $count Lines read"

[root@server199 ~]# ./
1 #!/usr/bin/perl
2 # print real UID
3 print "Real UID: $4 # print real GID
5 print "Real GID: $(n";
6 # print effective UID
7 print "Effective UID: $>n";
8 # print effective GID
9 print "Effective GID: $)n";

Total 9 Lines read

During Execution of the script we specify One command line Argument i.e. the name of any file. Then this script make the use of while-read loop for reading and displaying the file line by line.

!Enjoy Linux

Kuldeep Sharma