Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (2 votes)
179 views

Deep Unix & Linux Programming Lab DD

This document contains details of practical 1 for the subject "UNIX & Linux Programming". It provides an introduction to Linux and lists 53 basic Linux commands along with examples of their usage. The commands covered include file manipulation, directory navigation, process management and more.

Uploaded by

Deepak Kathuria
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
179 views

Deep Unix & Linux Programming Lab DD

This document contains details of practical 1 for the subject "UNIX & Linux Programming". It provides an introduction to Linux and lists 53 basic Linux commands along with examples of their usage. The commands covered include file manipulation, directory navigation, process management and more.

Uploaded by

Deepak Kathuria
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 46

7416039

PRACTICAL FILE

OF
“UNIX & LINUX
PROGRAMMING”

CSE-407N

Submitted To:- Submitted By: -


Ms. Meghavi Rana Deepak Kathuria
Assistant Professor Roll No.:-7416039
CSE Dept. B.Tech CSE 7th sem

SAMALKHA GROUP OF INSTITUTIONS,


SAMALKHA (PANIPAT)
KURUKSHETRA UNIVERSITY, KURUKSHETRA
APPROVED BY AICTE
7416039

INDEX
S.N
NAME OF THE PRACTICAL Date Signature
O
Familiarize with Unix/Linux logging/logout
1
and simple commands.

2 Familiarize with VI editor

Using bash shell develop simple shell


3
programs
Develop advanced shell Scripts using grep
4
& fgrep and sed
Learning of Installation and up gradation of
5
LINUX OS
Install LINUX on a PC having some other
6 previously installed operating system. All
operating systems should be usable

Compile and debug various C programs


7
using different options

As supervisor create and maintain user


accounts, learn package installation, taking
8 backups, creation of scripts for file and user
management, creation of startup and
shutdown scripts using at, cron etc.
7416039

Practical 1

AIM: Familiarize with Unix/Linux logging/logout and simple commands.

Introduction:

In 1991, a student at the University of Helsinki named Linus Torvalds found himself
dissatisfied with his operating system. Torvalds thought that the UNIX OS might be
better suited to him to accomplish his work. UNIX although powerful, was expensive,
so he began writing his own version of UNIX. Torvalds created a new OS or kernel
called Linux. The first real version of Linux (Version 1.0) was available for public use
in 1994.

Although many people might refer to Linux as the operating system and included
software, strictly speaking, Linux is the operating system kernel, which comes with a
distribution of software. Linux comes with source code, so you can change or
customize the software to adapt to your needs.

Linux is a great operating system, rich in features adopted from other versions of
UNIX.

Why linux?

Linux is a UNIX-like Operating System

Linux is as similar to UNIX as the various UNIX versions are to each other.
Conceptually, anything that can be done with another version of UNIX can be done
with the Linux operating system, although the means may vary slightly.

Multi-user and Multi-tasking

Linux is a multi-user and multi-tasking operating system. That means that more than
one person can be logged on to the same Linux computer at the same time. (Of
course, each user needs his own terminal.). The same user could even be logged into
their account from two or more terminals at the same time. Linux is also multi-tasking
i.e. a user can have more than one process (program) executing at the same time.

Wide hardware support

Linux supports most pieces of modern x86-compatible PC hardware. In early days of


Linux, hardware support was limited; today, Linux support has become a checklist
item for hardware vendors.

Fully supported

Linux is fully supported distribution. Red Hat Inc. provides many support programs
for the smallest to the largest companies.
7416039

Commands:

1. cal - Cal displays a simple calendar

$ cal
   November 2009
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

2. date - Display the current time in the given FORMAT, or set the system date.

$ date
Wed Nov 18 09:23:49 IST 2009

3. cd-Changes the directory to the directory specified

[computer@localhost ~]$ cd unix
[computer@localhost unix]$

4.who - show who is logged on

$ who
computer :0           Jun 29 23:58
computer pts/1        Jun 29 23:59 (:0.0)

5.whoami-Print the user name associated with the current effective user ID.

[computer@localhost unix]$ whoami
computer
6. w - Show who is logged on and what they are doing.

$ w
 
7. tty - print the file name of the terminal connected to standard input

[computer@localhost unix]$ tty
/dev/pts/1

8. pwd - print name of current/working directory

[computer@localhost unix]$ pwd
/home/computer/unix
7416039

9. mkdir- Create the DIRECTORY(ies), if they do not already exist.

[computer@localhost unix]$ mkdir –v linux
mkdir: created directory `linux’

10. rmdir -Remove the DIRECTORY(ies), if they are empty.

rmdir linux

11. rm - remove files or directories

$ rm file4

12. Touch - change file timestamps

$ touch file4

13. cat - concatenate files and print on the standard output

$ cat > file1
This is the first file
Good Bye!

14. wc - print the number of newlines, words, and bytes in files

$ wc file1
 2  7 33 file1

15. ls - list directory contents

$ ls
file1  file2  file3  file4  file5

16. cp - copy files and directories

$ cp file1 file2

17. mv - move (rename) files

$ mv file5 dir1

18. passwd - update a user’s authentication tokens(s)

[root@localhost ~]# passwd user1
Changing password for user user1.
7416039

New UNIX password:
BAD PASSWORD: it is based on a dictionary word
Retype new UNIX password:
passwd: all authentication tokens updated successfully.

19. echo - display a line of text

echo "This is our First Practical"
This is our First Practical

20. set – To display list of System variables.

$ set
BASH=/bin/bash
PATH=/usr/kerberos/bin:/usr/local/bin:/usr/bin:/bin:/usr/
X11R6/bin:/home/computer:/home/computer/bin
PIPESTATUS=([0]="0")
PPID=4379
PS1='[\u@\h \W]\$ '
PS2='> '
PS4='+ '
PWD=/home/computer

21. more - file perusal filter for crt viewing

$ Info | more

22.less - opposite of more

$ Info | less

23. man - display the on-line manual pages

$ man ls

24. info - read Info documents

$ info echo

25.type – command to know the location of command file

$  type ls
ls is /bin/ls

26. which - which returns the pathnames of the files which would be executed in the
current environment
$ which ls
/bin/ls
7416039

27. uname- the uname command with the -n option tells the machine name in the
network
$ uname -n
Linux

28. bc- acts as a character based-calculator


$bc
2+5
7

29. tput-can be used with arguement clear to clear the screen and also position the
cursor at a specific position using cup argument

$ tput clear

$tput cup 10 20

30. script-Script makes a typescript of everything printed on your terminal

$ script
Script started, file is typescript

31. cmp - Compare two files byte by byte.

$cmp file1 file2


file1 file2 differ: byte 2, line 1

32. comm – shows unique line of each fille and line common to both
$ comm file1 file2
hello
hi
how are you
this is unix

33. diff – displays file differences and tells which lines in one file have to be changed
to
make two files identical.

$ diff file1 file2

1,2c1,2
< hello
< this is unix
---
> hi
> how are you
7416039

34. file – tells the type of the data contained inthe file.

~$ file file1
file1: ASCII text

35. chmod – set the permission of the file.


$ chmod u+x file1 - assign executable permission to the user for the file1
$ chmod 111 file1 - assign executable permission to user,group and other.

36. chown - changhe owner of the file


$ chown own1 file1

37. chgrp - change group of the file


$ chgrp own1 file1

38. head – displays the top of the line


$ head file1

39. tail – displays the end of line


$ tail file1

40. nl – for numbering the lines


$ nl file1
1 hello
2 this is unix

41. od – displays octal value of the contents of the file


$ od file1
0000000 062550 066154 005157 064164 071551 064440 020163 067165
0000020 074151 000012
0000023

42. pr – prepares file for prnting by ading suitable headers, footers and formated text

$ pr file1

2009-11-20 22:32 file1 Page 1

hello
this is unix

43. cut – to slice a file vertically

$cut -c1-4 file1


hell
this
7416039

44. sort – Used for sorting function


$ sort file2
00
11
33

45. uniq – used to display uniqu lines of file


$ uniq file2
11
33
00

46. spell – used for spelling check


$ spell file

47. ln – used to create link of the files


$ ln file linkfile
$ ln -s file linkfile

48. df – to know the free disk space


$ df file1
Filesystem 1K-blocks Used Available Use% Mounted on
/host/ubuntu/disks/root.disk
2765720 2022760 602468 78% /

49. du – to know the consumption of any file or directory


$ du file1
4 file1

50. find - Recursively examines a directory tree to look for files either by name or by
matching one or more file attributes
find 'path' 'selection criteria' 'action'

$ find / -name abc -print


$ find / type -d -print

51. gzip – Used for compression of large file so that they consume a fraction of their
original file.

$ gzip file1

52. escaping – The Backslash (\) - removes the meaning of the matacharacters

$ ls chap*
chap1 chap2 chap*

$ ls chap\*
chap*
7416039

53. tee – Splits the its input into two components one is saved in file and other goes to
Standard output

$ ls | tee file2

file12

file1.gz

file2

54. grep – scans the file for the occurences of a pattern and depending upon the
option displays lines containing the selected pattern or the line number containing the
pattern etc.

$ grep 'pat' file : prints the lines of 'file' containg the pattern 'pat'
$ grep -c 'pat' file : prints the number of occurences of the pattern 'pat' in file 'file'.
$ grep -n 'pat' file : prints the line containg the pattern 'pat' with line number
$ grep -v 'pat' file : prints the line not containg the pattern 'pat'
$ grep -f file1 file2 : prints the line containg the pattern(s) stored in file1 .

55. egrep - egrep expands pattern matching capabilities of grep.


$ egrep 'abc | cde' file1 : Locates lines containg either abc or cde

56. fgrep – It also extends pattern matching capabilities of grep


$ fgrep 'abc
cde' file1

Locates lines containg either abc or cde both are placed in separate line with
command
7416039

Practical 2

AIM: Familiarize with VI editor.

Introduction:

vi (pronounced vee-EYE, short for “visual”) provides basic text editing capabilities.
Three aspects of vi make it appealing. First, vi is supplied with all UNIX systems.
You can use vi at other universities or any businesses with UNIX systems.
Second, vi uses a small amount of memory, which allows efficient operation
when the network is busy. Third, because vi uses standard alphanumeric keys for
commands, you can use it on virtually any terminal or workstation in existence
without having to worry about unusual keyboard mappings. As a point of
interest, vi is actually a special mode of another UNIX text

Starting vi:

To start VI, enter:

vi filename RETURN

where filename is the name of the file you want to edit. If the file does not exist, vi
will create it for you. You can also start vi without giving any filename. In this case, vi
will ask for one when you quit or save your work.

Modes in VI

There are three basic modes of vi explained as follows with diagram:

Command mode
This is the default when you enter vi. In command mode, most letters, or short
sequences of letters, that you type will be interpreted as commands, without
explicitly pressing Enter . If you press Esc when you're in command mode,
your terminal will beep at you. This is a very good way to tell when you're in
command mode.

Insert mode
7416039

In insert mode, whatever you type is inserted in the file at the cursor position.
Type any of the given characters a,A,I,I,o,O,r,R,s,S to enter insert mode from
command mode; press Esc to end insert mode, and return to command mode.

Input Last Line


Mode Mode

[Esc] [Enter]
i,I,a,A,o,O,r, :
R,s,S

Command
Mode

:x, :q
vi foo And ZZ

Shell

Line mode
Use line mode to enter line oriented commands. To enter line mode from
command mode, type a colon ( : ). Your cursor moves to the bottom of the
screen, by a colon prompt. Type a line mode command, then press Enter. Any
sensible command from the Unix line editor ex will work, and a few are good
to know about. These commands are indicated in this handout by a colon in
front of the command. Each time you use a line mode command, you must
type a colon to enter line mode, then type the command by the colon prompt at
the bottom of the screen, then press Enter when you finish typing the
command.For example some commamds are :q, :wq, :q!, :x etc

Some vi editor commands:

1)Inserting Text(i and I) :


7416039

To insert at current cursor position, press i . The character doesn’t show up on screen,
but pressing this key changes mode from Command to Input. While i can be used to
insert text anywhere in a line, I inserts text only at the beginning of a line.

2)Appending Text(a and A) :

To append text to right of the cursor position, use a To append text at the end of a line
use A.

3)Opening a New Line(o and O) :

You can open(i.e., insert) a new line by positioning the cursor at any point in a line
and pressing o opens new line below and to open a line above the current line, use O.

4)Replacing Text(r, R, s and S) :

To replace a single character with another, you should use r and to replace more than
a single character, use R which replaces text as cursor moves right.

To replace a single character with multicharacter text, take your cursor to that point
and then press s and to replace entire line, use S

5)Saving and Quitting(:wq and :x) :

The Last Line Mode offers two ways of saving and quitting - :x and :wq. These
commands return you to shell.
:w saves the work but not return to the shell.

6)Aborting Text(:q) :

You can abort editing process and quit the editing mode without saving the buffer. To
quit editor if buffer hasn’t changed :

:q[Enter]

If you don’t want to save changes made in buffer, you can use

:q![Enter]

7) Deleting characters(x,X) – Command Mode


7416039

x: The character is removed from the sight, and the text on the right left to fill up the
space.

X: Delete the character on the left but the character under the position is not deleted.

8)Finer deletion:

d$: deletes till and of line from the current cursor position which can be pasted using
p or
P
dd: deletes the current line

9)Yanking

y$: copies till end of line from the current cursor position
yy: copies the current line

10) Searching pattern

/pat: Searches forward for pattern pat


?pat: Searches backward for pattern pat

11) Search and replace(:s) – Example

:3,10s/pat1/pat2/g –search line 3 to 10 for all occurrences of pat1 and replaces with
pat2.

:$s/pat1/pat2/g - search current line for all occurrences of pat1 and replaces with
pat2.

:.,$/pat1/pat2 - search from current line to all successive lines for first occurrences of
pat1 and replaces with pat2.
7416039

Practical 3

AIM: Using bash shell develop simple shell programs.

How to use Shell


To use shell (You start to use your shell as soon as you log into your system) you have
to simply type commands.

What is Shell Script?


Normally shells are interactive. It means shell accept command from you (via
keyboard) and execute them. But if you use command one by one (sequence of 'n'
number of commands), then you can store this sequence of command to text file and
tell the shell to execute this text file instead of entering the commands. This is known
as shell script.
Shell script defined as:
"Shell Script is series of command written in plain text file”.

Why to Write Shell Script?


 Shell script can take input from user, file and output them on screen.
 Useful to create our own commands.
 Save lots of time.
 To automate some task of day today life.
 System Administration part can be also automated.

How to write shell script


Following steps are required to write shell script:
(1) Use any editor like vi to write shell script.
The first line always begin with #! And is fllowed by pathname of the shell to be used
for running script. This line is called interpreter line. Here it is Bourne shell.

# is the comment character and can be placed anywhere within a line.

(2) After writing shell script set execute permission for your script as follows
syntax: chmod permission your-script-name
Examples:
$ chmod +x your-script-name
$ chmod 755 your-script-name

(3) Execute your script as


syntax:
sh your-script-name
./your-script-name
7416039

Examples:
$ sh first.sh
$ ./first.sh

Some Shell Programs

Program 1: Write a non-interactive script

# !/bin/sh
echo "Today's Date is `date`"
echo "user logged in are: `who`"
echo "Current Directory is: `pwd`"

Output:
Today's Date is Mon Nov 16 08:33:32 EST 2009
user logged in are: computer tty7 2009-11-16 08:13 (:0)
computer pts/0 2009-11-16 08:25 (:0.0)
Current Directory is: /home/computer

Program 2: Write an Interactive script

# !/bin/sh
echo "What's your name ? "
read name
echo "Hello $name,Welcome to UNIX and LINUX"

Output:
What's your name ?
ram
Hello ram,Welcome to UNIX and LINUX

Program 3: Write a program to add two numbers.

# !/bin/sh
echo "Enter the two numbers"
read num1 num2
num3=`expr $num1 + $num2`
echo "Sum of the two numbers is $num3"
7416039

Output:
Enter the two numbers
23
Sum of the two numbers is 5

Program 4: Write a script to verify Password

# !/bin/sh

VALID_PD="ABC123@#"
echo "Enter the password"
read password
if [ $password == $VALID_PD ]
then
echo "Your password has been verified"
else
echo "You have entered wrong password"
fi

Output:
Enter the password
abc#@123
You have entered wrong password
Enter the password
ABC123@#
Your password has been verified

Program 5: Write a script to find a pattern in file using grep.

# !/bin/sh

echo "Enter the file name"


read file
echo "Enter the pattern to be searched"
read pattern
echo "Searching for $pattern in the file $file"
grep "$pattern" $file

Output:
Hello!
Welcome to the UNIX
Enter the file name
searchfile
7416039

Enter the pattern to be searched


Welcome
Searching for Welcome in the file searchfile
Welcome to the UNIX

Program 6: Write a script to check whether a number is even or odd.

# !/bin/sh

echo "Enter the number "


read num
if [ `expr $num % 2` -eq 0 ]
then
echo "The number is even"
else
echo "The number is odd"
fi

Output:
Enter the number
2
The number is even
Enter the number
3
The number is odd

Program 7:Write a script to add two numbers supplied as command line


arguments.

# !/bin/sh

if [ $# -ne 2 ]
then
echo "Usage - $0 x y"
echo "x and y are the numbers to be add"
exit 1
fi
echo "Sum of the two numbers is `expr $1 + $2`"

Output:
$ ./sumcommand 2 3
Sum of the two numbers is 5
7416039

$ ./sumcommand
Usage - ./sumcommand x y
x and y are the numbers to be add

Program 8: Write a script to find greatest of the three numbers given as command
line arguments.

# !/bin/sh

if [ $# -ne 3 ]
then
echo "$0: all the three arguments have not given"
exit 1
fi

num1=$1
num2=$2
num3=$3

if [ $num1 -gt $num2 ] && [ $num1 -gt $num3 ]


then
echo "$num1 is biggest of the three"

elif [ $num2 -gt $num1 ] && [ $num2 -gt $num3 ]


then
echo "$num2 is biggest of the three"

elif [ $num3 -gt $num2 ] && [ $num3 -gt $num1 ]


then
echo "$num3 is biggest of the three"

elif [ $num1 -gt $num2 ] && [ $num1 -gt $num3 ] && [ $num2 -eq $num3 ]
then
echo "All the three numbers are equal"

else
echo "Biggest of the number can not be found"
fi

Output:

$ ./biggest
./biggest: all the three arguments have not given
$ ./biggest 1 2 1
2 is biggest of the three
7416039

Program 9: Write a script to print numbers as 5,4,3,2,1 using while loop.

# !/bin/sh

i=5
while test $i != 0
do
echo "$i"
i=`expr $i - 1`
done

Output:
5
4
3
2
1

Program 10: Write a script using case to perform basic mathematics operations as
+) for addition, -) for subtraction, x|X) for multiplication, /) for division.

# !/bin/sh

if test $# = 3
then
case $2 in
+) let z=$1+$3;;
-) let z=$1-$3;;
/) let z=$1/$3;;
x) let z=$1*$3;;
*) echo "Warning - $2 invalid operator "
exit;;
esac
echo "Answer is $z"
else
echo "Usage -$0 value1 operator value2"
fi

Output:
./calcimenu 2 + 3
7416039

Answer is 5
$ ./calcimenu 2 / 3
Answer is 0
$ ./calcimenu 2 - 3
Answer is -1
$ ./calcimenu 2 x 3
Answer is 6
Program 11: Use case to offer five items menu
1. List of files 4. Users of the system
2. Process of user 5. Quit to UNIX or LINUX
3. Today’s Date

# !/bin/sh

echo "MENU"
echo "1. List of Files"
echo "2. Process of user"
echo "3. Date"
echo "4. Users of System"
echo "5. Quit to UNIX or LINUX"
echo "Enter the choice"
read choice
case $choice in
1) ls -l;;
2) ps;;
3) date;;
4) who;;
5) exit;;
*) echo "Invalid operator"
esac

Output:

./itemmenu
MENU
1. List of Files
2. Process of user
3. Date
4. Users of System
5. Quit to UNIX or LINUX
Enter the choice
3
Mon Nov 16 10:09:07 EST 2009

./itemmenu
MENU
1. List of Files
2. Process of user
7416039

3. Date
4. Users of System
5. Quit to UNIX or LINUX
Enter the choice
4
computer tty7 2009-11-16 08:13 (:0)
computer pts/0 2009-11-16 08:25 (:0.0)

PRACTICAL-4

AIM : Develop advanced shell Scripts using grep & fgrep and sed.

Script-1 : Script to delete all blank lines from a file using grep.

#!/bin/bash

echo -n "Enter the name of file : "


read filename

echo "File without any blank lines is : "


grep -v "^$" $filename

Output : $ ./prg1.sh
Enter the name of file : file1
File without any blank lines is :
This is 4th practical.
Today is the Friday.
There are many blank lines in this file.

Script-2 : Script to delete all blank lines from a file using sed.

#!/bin/bash

echo -n "Enter the name of file : "


read filename

echo "File without any blank lines is : "


sed -n '/^$/ !p' $filename

Output : $ ./prg2.sh
Enter the name of file : file1
File without any blank lines is :
This is 4th practical.
Today is the Friday.
There are many blank lines in this file.
7416039

Script-3 : Script to check whether a particular user is logged-in or not using grep.

#!/bin/bash
echo -n "Enter the user name : "
read username

if [ `who | grep -c "$username"` -eq 0 ]


then
echo User is not logged in.
else
echo User is logged-in.
fi

Output : $ ./prg3.sh
Enter the user name : computer
User is logged-in.

Script-4 : Script to check whether a particular user is logged-in or not using sed.

#!/bin/bash
echo -n "Enter the user name : "
read username

who | sed -n "/$username/ p"

Output : $ ./prg4.sh
Enter the user name : computer
computer tty7 2009-11-20 06:32 (:0)
computer pts/0 2009-11-20 06:33 (:0.0)

Script-5 : Script to write every line of the file twice.

#!/bin/bash

echo -n "Enter the name of file : "


read filename

sed 'p' $filename

Output : $ ./prg5.sh
Enter the name of file : file2
1)This is file2.
1)This is file2.
2)I am practicing for Unix & Linux.
2)I am practicing for Unix & Linux.

Script-6 : Script to select all but not last line.

#!/bin/bash
7416039

echo -n "Enter the name of file : "


read filename

sed -n '$ !p' $filename

Output : $ ./prg6.sh
Enter the name of file : file2
1)This is file2.

Script-7 : Script to double space a file.

#!/bin/bash
echo -n "Enter the name of file : "
read filename
sed 'a

' $filename

Output : $ ./prg7.sh
Enter the name of file : file2
1)This is file2.

2)I am practicing for Unix & Linux.

Script-8 : Script to locate the line containing the last occurrence of a pattern.

#!/bin/bash
echo -n "Enter the name of file : "
read filename

echo -n "Enter the pattern : "


read pattern

grep "$pattern" $filename | tail -1

Output : $ ./prg8.sh
Enter the name of file : file2
Enter the pattern : Linux
2)I am practicing for Unix & Linux.

Script-9 : Script to find lines longer than 20 characters using grep.

#!/bin/bash
echo -n "Enter the name of file : "
read filename

grep ".\{21\}" $filename


7416039

Output : $ ./prg9.sh
Enter the name of file : file2
2)I am practicing for Unix & Linux.

Script-10 : Script to see whether a file exists or not.

#!/bin/bash

echo -n "Enter the name of file : "


read filename

if [ `ls -1 | grep "^$filename$" | wc -l` -eq 1 ]


then
echo File exists.
else
echo "File doesn't exists."
fi

Output : $ ./prg10.sh
Enter the name of file : file2
File exists.

Script-11 : Script to count the number of lines in a file.

#!/bin/bash

echo -n "Enter the name of file : "


read filename

echo -n "Number of lines in $filename are : "


wc -l < $filename

Output : $ ./prg11.sh
Enter the name of file : file1
Number of lines in file1 are : 10

Script-12 : Script to count the number of characters in a file.

#!/bin/bash

echo -n "Enter the name of file : "


read filename

echo -n "Number of characters in $filename are : "


wc -c < $filename

Output : $ ./prg12.sh
7416039

Enter the name of file : file2


Number of characters in file2 are : 59

Script-13 : Script to count the number of blank lines in a file.

#!/bin/bash
echo -n "Enter the name of file : "
read filename

echo -n "Number of blank lines in $filename are : "


grep "^$" $filename | wc -l

Output : $ ./prg13.sh
Enter the name of file : file1
Number of blank lines in file1 are : 7

Script-14 : Script to find the list of all users on a system.

#!/bin/bash

echo "Following users are logged-in : "


who | cut -d\ -f1

Output : $ ./prg14.sh
Following users are logged-in :
sahil
computer
computer

Script-15 : Script to concatenate two files and insert some text in between them.

#!/bin/bash
echo -n "Enter the name of first file : "
read filename1

echo -n "Enter the name of second file : "


read filename2
cat $filename1 - $filename2

Output : $ ./prg15.sh
Enter the name of first file : file1
Enter the name of second file : file2
7416039

This is 4th practical.

Today is the Friday.

There are many blank lines in this file.


This text is added by terminal.
This text is added by terminal.
1)This is file2.
2)I am making practicals of Unix & Linux.

Script-16 : Script to find the lines whose length is between 20 and 50 characters using
grep.

#!/bin/bash
echo -n "Enter the name of the file : "
read filename
echo "Lines whose length is between 20 and 50 characters are : "
grep "^.\{21,49\}$" $filename

Output : $ ./prg16.sh
Enter the name of the file : file1
Lines whose length is between 20 and 50 characters are :
This is 4th practical.
there are many blank lines in this file.

Script-17 : Script to find the lines whose length is between 20 and 50 characters using
sed.

#!/bin/bash
echo -n "Enter the name of the file : "
read filename

echo "Lines whose length is between 20 and 50 characters are : "


sed -n '/^.\{21,49\}$/ p' $filename

Output : $ ./prg17.sh
Enter the name of the file : file1
Lines whose length is between 20 and 50 characters are :
This is 4th practical.
there are many blank lines in this file.

Script-18 : Script to find the lines containing less than 20 characters using grep.
7416039

#!/bin/bash
echo -n "Enter the name of the file : "
read filename

echo "Lines whose length is less than 20 characters are : "


grep "^.\{0,19\}$" $filename

Output : $ ./prg18.sh
Enter the name of the file : file2
Lines whose length is less than 20 characters are :
1)This is file2.

Script-19 : Script to find the lines containing less than 20 characters using sed.

#!/bin/bash
echo -n "Enter the name of the file : "
read filename

echo "Lines whose length is less than 20 characters are : "


sed -n '/^.\{0,19\}$/ p' $filename

Output : $ ./prg19.sh
Enter the name of the file : file2
Lines whose length is less than 20 characters are :
1)This is file2.

Script-20: The fgrep and egrep command:

The fgrep and egrep command are advanced pattern matching


command. The fgrep command doesn’t use any meta character for its
searched pattern. The primary advantages of fgrep it that it can also
search two or more than two strings simultaneously.
The fgrep command can be used like this:

$fgrep ‘good
bad
great’ userfile
$

Here a single quote is used to mark three strings as one argument.


Here we are going to search three different strings good, bad, and
great. The egrep command is used to search this in a more compact
form than fgrep command:
7416039

$egrep ‘good | bad | great’ userfile

The egrep uses an or ( | ) operator to achieve this. Therefore egrep


command is more compact and more versatile than fgrep. Another
achievement of egrep is that we can make groups of different patterns.
If we use | as operator.

$egrep ‘sunil | rohan gavasker ‘ players

Here sunil is first pattern and everything to the right is considered as


second pattern.
If we want to search both sunil gavasker and rohan gavasker use this:

$egrep ‘(sunil | rohan)‘ players

Example:

$ cat employee1.sh
# script : employee1.sh-interactive version
# the pattern and file name will be supplied by the user
echo “\n enter the pattern to be searched :\c”
read pname
echo “\n enter the file to be used :\c”
read filename
echo “\n searching for $ pname from file $ filename\n”
grep “ $ pname “ $ filename
echo “\n selected record shown above \n”
\c
7416039

Practical 5

AIM: Learning of Installation and up gradation of LINUX OS.

Installation Of Linux

Before getting started, one should know that you can easily change your configuration
choices. If you realize that you have made a mistake, you can click back button to
retrace your steps and redo your choices. And, if you ever want to stop your
installation process, you can simply reboot your computer.

The point of no return comes at the end of the process, when the configuration is
written to your hard drive and the installation software starts to partition your hard
drive and write Linux to it. If you stop at this point, you need to reinstall an OS before
you can use the computer again.

The following stages of installation are to followed if

(a) you have a computer with no preinstalled OS


(b) you have a Windows computer and are willing to completely reformat your
hard disk, permanently erasing it contents
(c) finally, some Windows computers include secondary Windows partitions that
you can use on which to install Linux i.e. dual boot

Recommended Hardware Requirements:

1. Pentium-Class or better CPU


2. 128 MB or more RAM
3. 2-6 GB disk space depending on intended use
4. Bootable CD-ROM or 3 ½ “ floppy drive
5. For GUI interface, a mouse is also required
6. For systems that are part of network, a network card is also required

Software Requirements:
7416039

If you want to have Linux share your hard disk with Windows, you need to free up
your hard disk space which is previously acquired by Windows by the use of
following tools:

1. fips (First non-destructive interactive Partition Splitting


2. Partition Magic or any other software.

Remember before using these tools, you need to defragment your hard disk.

Information gathering:

1. During installation of Linux, one generally make three partitions: root, boot
and swap. So
(a) You need to decide how much of your hard disk drive you want to allocate to
root partition.
(b) You must decide how much space you want to allocate to swap partition.
(c) You must decide how much space you want to allocate to boot partition.

2. During installation, you will be able to perform administrative tasks such as


creating users, setting passwords etc.
3. If your computer is connected to a LAN that’s running TCP/IP, you will
probably want to contact your network administrator to get the following
information before installing linux.

Hostname of Machine :
Domain Name:
IPAddress:
Netmask:
DefaultGateway:
PrimaryNameserver:
2ndNameserver:
NFSServer(optional):
FTPServer(optional):

Installation stage 1: Starting the installation

This stage gets you started with the Linux Partition Process

1. Insert Linux installation CD #1 in the CD and then reboot the machine.

2. When the boot prompt appears, just press enter, to accept default options (graphical
installation method)

3. If asked for media check (in Fedora), click skip. (Does not ask in Red Hat)

4. When Linux has detected your hardware, the installation process starts and the
welcome message is displayed onscreen. Click the next button to proceed to the next
window.
7416039

5. After the welcome message screen disappears, the language selection window
appears.

6. Select a language and click next.

7. Select the keyboard configuration and then click next.

8. Select your mouse and click next.

9. Click next. The installation type window appears. (If you trying to install on a
Linux HDD, you will be asked whether to wish to upgrade or install a new copy; do
not select upgrade option.)

Installation stage 2: Disk Partitioning

In this stage you must decide where on your hard disk to install Linux, a process
called disk partitioning. Disk partitioning divides a disk into multiple sections. Linux
is then installed on the partitions, typically three to seven partitions.

10. Linux provides automatic and manual methods for creating disk partitions

Disk Partitioning for single boot: if you are not sure what to do then select automatic,
or else select manual partitioning and choose “Remove all partitions on this system”.

Disk Partitioning for dual boot: if you are not sure what to do then select automatic, or
else select manual partitioning and choose “Remove all Linux partition on this
system” or “Keep all partitions and use existing free space”.

Three partitions will be created automatically:

(a) Boot partition: Not more than 100MB


(b) Swap partition: 2.5 times of the physical ram available
(c) Root partition: allocate the rest of the hdd space for root partition (Note you can
also use any other partitioning scheme you may find suitable)

11. Review the three partitions and modify them if needed.

12. Click the next button. The boot loader configuration window appears. The boot
loader helps start your OS when you start your computer.

Installation stage 3: Configuring your network

13. If you are ready to configure your network and your computer has an Ethernet
adapter, make necessary changes, (if not sure accept default)

14. Misc. Settings: as applicable (if not sure, leave blank) This May show errors
(ignore them, and click next)

15. Select the medium Firewall option (default) and click the next button.
7416039

Installation stage 4: Configuring your options

16. Additional Language support window appears: accept default, English (U.S.A.)

17. Select your Time Zone: Click the dot representing a city closest to where you live.
Click next

18. Type your root password in both the root password and confirm text boxes. Click
Next.

19. Package Selection window appears- following packages to be selected. Click next

Installation stage 5: Validating your installation

At this stage, partitions you selected haven’t been written, no packages have been
written to your hard drive either. You can stop the installation process and go back to
your old computer by clicking the back button.

20. Click continue. Now the packages will start to install, the installation program will
ask you insert CDs.

21. After the installation is over, the server restarts. Before the system restarts, remove
the CD and any floppy disks in your drives.

Installation stage 6: Install and Configure the X Server

After restart, the final stage of installation will proceed. The last thing to do is install
and configure the X server. X server gives you a graphical environment to use Linux.

22. License Agreement: Yes.

23. Time & Date: Set as required.

24. Select your computer’s video card and memory and click next.

25. Display settings: (Very important, see below)

If the data shown on the screen is not correct, please change by Clicking
configuration. If your monitor is not detected, select Generic CRT, with appropriate
colour depth.

26. Remove all removable items and click next. Your system reboots.

POST INSTALLATION

After your computer reboots, setup agent starts. Setup agent automatically runs the
first time you boot your computer after installing Linux. The setup agent simplifies
the installation process by pushing some configuration work to the post-installation
7416039

phase. However Linux computer works fine whether or not you run the setup agent.
The purpose of setup agent is to fine-tune your computer.

The following steps shows how to use setup agent immediately after installation

1. When the Linux setup system starts, you see the welcome screen. Click
forward button to start the post-installation configuration process.
2. Create a user window opens. Enter a account name, the name of account
owner, and its password. Click forward.
3. After that date and time configuration window appears. Change the date and
time if required.
4. The sound card detected during installation is shown here-click the play test
sound button to test your computer. Click forward.
5. The update agent window appears. Click No, I don’t want to register my
system radio button. Click forward.
6. Install additional software screen opens. If you want to install new software
then insert the CD’s into the CD-Drive otherwise click forward.
7. The finished setup window opens. We are done and now the setup agent exits.

You can also run the setup agent anytime after booting the system also.

Important Directories
After installation some directories are created under the root(/) directory. There is a
directory called /home, where user files are stored. As a system administrator and
programmer, several other directories will be important to you. Here are a few, along
with their introduction what they do:

/bin ( binary )

The most essential Unix commands. The commands stored in this directory are
common to all users such as ls.

sbin

The /sbin/ directory is for executables used only by the root user. The executables in
/sbin/ are only used to boot and mount /usr/ and perform system recovery operations.

"/sbin typically contains files essential for booting the system in addition to the
binaries in /bin. Anything executed after /usr is known to be mounted (when there are
no problems) should be placed in /usr/sbin.

/boot

Location where the kernel and other files used during booting are sometimes stored
i.e. files which are accessed during booting time.

/etc
7416039

Files used by subsystems such as networking, NFS, and mail. Typically, these contain
tables of network services, disks to mount, and so on. Many of the files here are used
for booting the system or individual services of it i.e. configuration files ( system as
well as admin )

/etc/skel

Sample startup files you can place in home directories for new users.

/var

Administrative files, such as log files, used by various utilities i.e. log files & spooling
files are stored.

/var/spool

Temporary storage for files being printed sent by various users and so on.

/usr

this directory contains files that are accessed to all users.

/usr/bin

Other commands. The distinction between /bin and /usr/bin is arbitrary; it was
a convenient way to split up commands on early Unix systems that had small disks.

/usr/sbin

Commands used by the superuser for system administration i.e. this directory contain
admin commands which only root user can run

/usr/lib

Standard libraries, such as libc.a. When you link a program, the linker always
searches here for the libraries specified in -l options.

/usr/lib/X11

The X Window System distribution. Contains the libraries used by X clients, as well
as fonts, sample resources files, and other important parts of the X package. This
directory is usually a symbolic link to /usr/X11R6/lib/X11.

/usr/include

Standard location of include files used in C programs, such as <stdio.h>.


7416039

/usr/src

Location of sources to programs built on the system.

/usr/local

Programs and datafiles that have been added locally by the system administrator.

/dev

This directory contains the so-called device files, the interface between the filesystem
and the hardware (e.g., /dev/modem represents your modem in the system). The /dev/
directory contains file system entries which represent devices that are attached to the
system. These files are essential for the system to function properly.

/proc

Just as /dev is the interface between the filesystem and the hardware devices, /proc is
the interface between the filesystem and the running processes, the CPU and memory.
The files here (which are not real files, but rather virtual files generated on-the-fly
when you view them) can give you information about the environment of a certain
process, the state and configuration of the CPU, how your I/O ports are configured,
etc.

home

all users home dir are stored under home directories

lost + found

file system check procedure

misc,opt

The /opt/ directory provides storage for large, static application software packages.
A package placing files in the /opt/ directory creates a directory bearing the same
name as the package. This directory in turn holds files that otherwise would be
scattered throughout the file system, giving the system administrator an easy way to
determine the role of each file within a particular package.

For example, if sample is the name of a particular software package located within the
/opt/ directory, then all of its files could be placed within directories inside the
/opt/sample/ directory, such as /opt/sample/bin/ for binaries and /opt/sample/man/ for
manual pages.

Large packages that encompass many different sub-packages, each of which


accomplish a particular task, also go within the /opt/ directory, giving that large
package a standardized way to organize itself. In this way, our sample package may
7416039

have different tools that each go in their own subdirectories, such as


/opt/sample/tool1/ and /opt/sample/tool2/, each of which can have their own bin/,
man/, and other similar directories i.e. any third party s/w can be installed

mnt

The /mnt/ directory is for temporarily mounted file systems, such as CD-ROMs and
floppy disks.

root

root dir is the home dir of root user

tmp

temp files are stored

lib

The /lib/ directory should contain only those libraries that are needed to execute the
binaries in /bin/ and /sbin/. These shared library images are particularly important for
booting the system and executing commands within the root file system i.e. library
files are stored

Various types of files used in Linux are:-

FILE TYPE MEANING


- Ordinary file
D Directory
C Char special file
B Block special file
L Symbolic link
S Semaphore
P Named pipe
M Shared memory file
7416039

Practical 6

AIM: Install LINUX on a PC having some other previously installed


operating system. All operating systems should be usable.

Installation Of Linux

Information gathering:

1. During installation of Linux, one generally make three partitions: root, boot
and swap. So
(a) You need to decide how much of your hard disk drive you want to allocate to
root partition.
(b) You must decide how much space you want to allocate to swap partition.
(c) You must decide how much space you want to allocate to boot partition.

2. During installation, you will be able to perform administrative tasks such as


creating users, setting passwords etc.
3. If your computer is connected to a LAN that’s running TCP/IP, you will
probably want to contact your network administrator to get the following
information before installing linux.

Hostname of Machine :
Domain Name:
IPAddress:
Netmask:
DefaultGateway:
PrimaryNameserver:
2ndNameserver:
NFSServer(optional):
FTPServer(optional):

Installation stage 1: Starting the installation

This stage gets you started with the Linux Partition Process
7416039

1. Insert Linux installation CD #1 in the CD and then reboot the machine.

2. When the boot prompt appears, just press enter, to accept default options (graphical
installation method)

3. If asked for media check (in Fedora), click skip. (Does not ask in Red Hat)

4. When Linux has detected your hardware, the installation process starts and the
welcome message is displayed onscreen. Click the next button to proceed to the next
window.

5. After the welcome message screen disappears, the language selection window
appears.

6. Select a language and click next.

7. Select the keyboard configuration and then click next.

8. Select your mouse and click next.

9. Click next. The installation type window appears. (If you trying to install on a
Linux HDD, you will be asked whether to wish to upgrade or install a new copy; do
not select upgrade option.)

Installation stage 2: Disk Partitioning

In this stage you must decide where on your hard disk to install Linux, a process
called disk partitioning. Disk partitioning divides a disk into multiple sections. Linux
is then installed on the partitions, typically three to seven partitions.

10. Linux provides automatic and manual methods for creating disk partitions

Disk Partitioning for single boot: if you are not sure what to do then select automatic,
or else select manual partitioning and choose “Remove all partitions on this system”.

Disk Partitioning for dual boot: if you are not sure what to do then select automatic, or
else select manual partitioning and choose “Remove all Linux partition on this
system” or “Keep all partitions and use existing free space”.

Three partitions will be created automatically:

(a) Boot partition: Not more than 100MB


(b) Swap partition: 2.5 times of the physical ram available
(c) Root partition: allocate the rest of the hdd space for root partition (Note you can
also use any other partitioning scheme you may find suitable)

11. Review the three partitions and modify them if needed.

12. Click the next button. The boot loader configuration window appears. The boot
loader helps start your OS when you start your computer.
7416039

Installation stage 3: Configuring your network

13. If you are ready to configure your network and your computer has an Ethernet
adapter, make necessary changes, (if not sure accept default)

14. Misc. Settings: as applicable (if not sure, leave blank) This May show errors
(ignore them, and click next)

15. Select the medium Firewall option (default) and click the next button.

Installation stage 4: Configuring your options

16. Additional Language support window appears: accept default, English (U.S.A.)

17. Select your Time Zone: Click the dot representing a city closest to where you live.
Click next

18. Type your root password in both the root password and confirm text boxes. Click
Next.

19. Package Selection window appears- following packages to be selected. Click next

Installation stage 5: Validating your installation

At this stage, partitions you selected haven’t been written, no packages have been
written to your hard drive either. You can stop the installation process and go back to
your old computer by clicking the back button.

20. Click continue. Now the packages will start to install, the installation program will
ask you insert CDs.

21. After the installation is over, the server restarts. Before the system restarts, remove
the CD and any floppy disks in your drives.

Installation stage 6: Install and Configure the X Server

After restart, the final stage of installation will proceed. The last thing to do is install
and configure the X server. X server gives you a graphical environment to use Linux.

22. License Agreement: Yes.

23. Time & Date: Set as required.

24. Select your computer’s video card and memory and click next.

25. Display settings: (Very important, see below)


7416039

If the data shown on the screen is not correct, please change by Clicking
configuration. If your monitor is not detected, select Generic CRT, with appropriate
colour depth.

26. Remove all removable items and click next. Your system reboots.

Practical 7

AIM: Compile and debug various C programs using different options.

a)mv
Sol:
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
void main()
{
int fd1,fd2;
char buf[60];
char *p="/f2";
fd1=open("f2",O_RDWR);
fd2=open("f6",O_RDWR);
read(fd1,buf,sizeof(buf));
write(fd2,buf,sizeof(buf));
remove(p);
}

b)cp
Sol:
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
void main()
{
int fd1,fd2;
char buf[60];
7416039

fd1=open("f2",O_RDWR);
fd2=open("f6",O_RDWR);
read(fd1,buf,sizeof(buf));
write(fd2,buf,sizeof(buf));
close(fd1);
close(fd2);
}

C)ls Command
Sol:
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<dirent.h>
void main()
{
DIR *dp;
struct dirent *dirp;
dp=opendir(".");
while(dirp=(readdir(dp)!=NULL))
{
if(dirp->d_ino==0)
continue;
else
printf("%s \n",dirp->d_name);
}
}
7416039

Practical:8

Aim:-As supervisor create and maintain user accounts, learn package installation,
taking backups, creation of scripts for file and user management, creation of startup
and shutdown scripts using at, cron etc.

Create and Maintain User Account:


 useradd (in /usr/sbin):

useradd is a utility for adding new users to a UNIX system. It adds


new user information to the /etc/passwd file and creates a new home
directory for the user. When you add a new user, you should also set
their password (using the-p option on useradd, or using
the passwd utility):

# useradd bob
# passwd bob

Controlling user groups:

 groupadd (in /usr/sbin):

groupadd creates a new user group and adds the new information
to /etc/group:

# groupadd groupname

 usermod (in /usr/sbin):


7416039

Every user belongs to a primary group and possibly also to a set of


supplementary groups. To modify the group permissions of an
existing user, use

# usermod -g initialgroup username -G othergroups

where othergroups is a list of supplementary group names separated


by commas (with no intervening whitespace).

 groups

You can find out which groups a user belongs to by typing:

# groups username

Creation Of Startup And Shutdown Scripts:

Startup and shut down script has 3 parts

1.Original script in /sbin/init.d

2.Configuratiopn file for the script in /etc/rc.config.d


(configuration variables in /etc/rc.config.d to change the behavior of scripts in
/sbin/init.d.)

3.Symlink file for the scripts under /sbin/rc*.d/

How to enable startup/shutdown scripts

Step1 : First place the script under the directory /sbin/init.d/

Step2 : Then create a sym link to the script file

Start a service : ln -s /sbin/init.d/ur_script /sbin/rc3.d/S900urscript.rc

stop a service : ln -s /sbin/init.d/ur_script /sbin/rc3.d/K900Ur_script.rc

3. Place the configuration file under /etc/rc.config.d with required variables (optional)

For Examble : CRON service


7416039

/sbin/init.d/cron --> execution script


/etc/rc.config.d/cron --> configuration file
/sbin/rc2.d/S730cron --> start sequence symbolic link
/sbin/rc1.d/K270cron --> kill sequence symbolic link

Scheduling With the crontab Command to take backups

You can use the crontab command to run commands at regular times. For example,
you could schedule a backup of your files every Friday. Commands can be scheduled
to the minute.

If you want to schedule a command to run only once, look into the at command.

The crontab command works by reading a crontab file. A crontab file is a plain text
file that lists all the jobs you have scheduled.

Each line of the crontab file consists of the command with all its options and
arguments, and the date and time to run it.

By default, all users can set up their own crontab files. However, the root user can use
two files to control access:

/etc/cron.allow: If this file exists, only users listed in it can use crontab.

/etc/cron.deny: If this file exists, users listed in it cannot use crontab.

All crontab files are stored in the /var/spool/cron/crontabs/ directory. However, since
regular users do not have read or write permission to this directory, they must use the
crontab command to schedule jobs.

Cron, as supplied in Debian, has two purposes:

To run system jobs on a daily/weekly/monthly basis

To allow users to setup their own schedules

The system schedules are setup when the package is installed, via the creation of
some special directories:

/etc/cron.d
/etc/cron.daily
/etc/cron.hourly
/etc/cron.monthly
/etc/cron.weekly

Except for hte first one which is special, these directories allow scheduling of system-
wide jobs in a coarse manner. Any script which is executable and placed inside them
will run at the frequency which its name suggests.
7416039

For example if you place a script inside /etc/cron.daily it will be executed once per
day, every day.

The time that the scripts run in those system-wide directories is not something that an
administration typically changes, but the times can be adjusted by editing the file
/etc/crontab. The format of this file will be explained shortly.

The normal manner which people use cron is via the crontab command. This allows
you to view or edit your crontab file, which is a per-user file containing entries
describing commands to execute and the time to execute them.

You might also like