0% found this document useful (0 votes)
76 views48 pages

Foss Complete Lab Manual

Uploaded by

cherrybhai.gff
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
76 views48 pages

Foss Complete Lab Manual

Uploaded by

cherrybhai.gff
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

RAGHU ENGINEERING COLLEGE

Dakamarri(vill), BheemunipatnamMandal,
Visakhapatnam Dist, Andhra Pradesh, PIN-531162
(Approved by AICTE, New Delhi, Permanently Affiliated to Jntu-Gv College Of Engineering
Vizianagaram and Accreditated by NBA and NAAC 'A+ Grade')

2023-2024

II B.Tech- I-Semester(AR20)
STUDENT LABORATORY MANUAL

For

FOSS Lab

Prepared by

V.Avinash, Dept of CSE


Asst. Professor
FOSS Lab
AR20 - B. Tech. (Common to CSE & All Specializations)
II - B. Tech., I-Semester
L T P C
0 0 3 1.5

Course Code: 20CS3108 Internal Marks: 15


External Marks: 35

Course Objectives:
The course objectives of FOSS Lab are to discuss and make student familiar with the

• To learn about the significance of FOSS.


• To be familiarized the basic commands in Linux.
• To be familiarized with Linux Operating system.
• To be familiarized with shell scripting
Course Outcomes:
By the end of the course, the student will:

• Identify and apply various Linux commands.


• Create a new file from scratch or edit an existing file using vi editor.
• Develop shell and awk scripts for specific needs.

LAB EXPERIMENTS

1. Study of Unix/Linux command list:


cd, cal,cat, banner, touch, man,who,cat, cd, cp,MV, ls, mv, rm, mkdir, rmdir, echo, more, date,
history, chmod, pwd, cal,wc, sort, cut,paste, logout, shutdown.

2. Demonstration of VI editor
Session-1
a) Use vi editor to create a file called myfile.txt which contains some text.
b) Correct typing errors during creation.
c) Save the file
d) Logout of the system
Session-2
a) Log into the system
b) Open the file created in session 1
c) Add some text
d) Change some text
e) Delete some text
f) Save the Changes
g) Logout of the system

3. a) Write a shell script to generate the mathematical tables.


b) Write a shell script to find the factorial of a given number.
c) Write a shell script that computes the gross salary of a employee according to the
following rules:
i) If basic salary is < 1500 then HRA =10% of the basic and DA =90% of the basic.
ii) If basic salary is >=1500 then HRA =Rs500 and DA=98% of the basic

4. a) Write a shell script (small calculator) that adds, subtracts, multiplies and divides the two
given numbers. There are two division options: one returns the quotient and the other remainder.
The script requires three arguments: the operation to be used and the two integers. The operation
is specified by options:
Add -a
Subtract-s
Multiply -m
Quotient -c
Remainder –r
b) Write a shell script to accept student number, name, and marks in five subjects. Find total,
average and grade.
Rules:
Avg>=80 then grade A
Avg<80&&Avg>=70 then grade B
Avg<70&&Avg>=60 then grade C
Avg<60&&Avg>=50 then grade D
Avg<50&&Avg>=40 then grade E
Else grade F
c) Write a shell script to find the GCD of two given numbers.

5. a) Write a shell script to display string palindrome from given arguments.


b) Write a shell script which will display Armstrong numbers from given arguments.
c) Write a shell script to display reverse numbers from given argument list.

6. a) Write a shell script to find largest element in a array


b) Write a shell script to determine whether a given number is a prime number or not.
c) Write a shell script to generate a Floyd triangle for a given value.

7. a) Write a shell script to print all the primes below a given number is a prime number.
b) Write a shell script to print the first ‘n’ Fibonacci numbers.
c) Write a shell script which displays the list of all files in a given directory.

8. a) Write a shell script to sort elements of given array by using selection sort.
b) Write a shell script to search given number using binary search.

9. a) Write a sed command that deletes the first character in each line in a file.
b) Write a sed command that deletes the character before the last character in each line in a
file.
c) Write a sed command that swaps the first and second words in each line in a file.
10. a) Write an awk program to print sum, avg of students marks list
b) Write an awk program to display students pass/fail report.
c) Write an awk program to count the no. of vowels in a given file.
Objective:

1. Study of Unix/Linux command list:


cd, cal ,cat, banner, touch, man, who, cat, cp, ls, mv, rm, mkdir, rmdir, echo,
more, date, history, chmod, pwd, wc, sort, cut, paste, logout, shutdown.

a) cd - To change directory - change the current working directory to a specific Folder.

Description:
If directory is given, changes the shell's working directory to directory. If not, changes to HOME
(shell variable). If the shell variable CDPATH exists, it is used as a search path. If directory
begins with a slash, CDPATH is not used. If directory is '-', this will change to the previous
directory location (equivalent to $OLDPWD ). The return status is zero if the directory is
successfully changed, non-zero otherwise.
Options:
Tag Description
-P Do not follow symbolic links
-L Follow symbolic links (default)

Procedure:

1.Open terminal and create a directory


2.change the directory by using the cd command
3.check whether directory changed or not using pwd

Examples:
Move to the sample folder
$ cd /usr/local/sample
$ pwd
/usr/local/sample
Change to another folder
$ cd /var/local/logs
$ pwd
/var/local/logs
Quickly get back
$ cd -
$ pwd
/usr/local/sample
Move up one folder
$ cd ..
$ pwd
/usr/local/
Get back to original location
$ cd
$ pwd
/usr/local/

b) cal - To display a calendar

Syntax: cal [-mjy] [month] [year]

Description:
A single parameter specifies the 4 digit year (1 - 9999) to be displayed. Two parameters denote
the Month (1 - 12) and Year (1 - 9999). If arguments are not specified, the current month is
displayed. A year starts on 01 Jan.

Options:
Tag Description
-m Display monday as the first day of the week.
-j Display julian dates (days one-based, numbered from January 1).
-y Display a calendar for the current year.

Procedure:

1.Open terminal and enter cal command


2.It will display the calendar

Examples:
To display current month's calendar
$ cal
April 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
To display feb 2015 calendar
$ cal 2 2015
February 2015
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
To display complete year calendar.
$ cal -y

c) cat - Concatenate and print the content of files.


Syntax:
cat [Options] [File]...
Description:
Cat command concatenate FILE(s), or standard input, to standard output. With no FILE, or
when FILE is -, it reads standard input.
Options:
Tag Description
-A, --show-all equivalent to –Vet
-b, --number-nonblank number nonblank output lines
-e equivalent to -vE
-E, --show-ends display $ at end of each line
-n, --number number all output lines
-s, --squeeze-blank never more than one single blank line
-t equivalent to -vT
-T,--show-tabs display TAB characters as ^I
-u (ignored)
-v, --show-nonprinting use ^ and M- notation, except for LFD and TAB. display this help and exit
--help display this help and exit
--version output version information and exit

Procedure:

1.Create a file using cat command


2.check the file created or not using cat command

Examples:
Create two sample files
#sample.txt
This is a sample text file
#sample1.txt
This is a another sample text file
To display content of a file.
$ cat sample.txt
This is a sample text file
To display content of all txt files.
$ cat *.txt
This is a another sample text file
This is a sample text file
To concatenate two files.
$ cat sample.txt sample1.txt > sample2.txt
$ cat sample2.txt
This is a sample text file
This is a another sample text file
To put content of a file in a variable.
$ variable_content = 'cat sample.txt'

d) Banner –banner command is used to print the ASCII character string in large letter to standard
output.

Syntax:
Banner < text>

Procedure:

1.Enter any content using Banner command


2.It display the content in large letters.

Example:
$ Banner Raghu Engineering College

e) touch - change file timestamps


Syntax:
touch [OPTION]... FILE...
Tag Description
-a change only the access time
-c, --no-create
do not create any files
-d, --date=STRING
parse STRING and use it instead of current time
-f (ignored)
-m change only the modification time
-r, --reference=FILE
use this file’s times instead of current time
-t STAMP use [[CC]YY]MMDDhhmm[.ss] instead of current time
--time=WORD
change the specified time: WORD is access, atime, or use: equivalent to -
a WORD is modify or mtime: equivalent to -m
--help display this help and exit
--version
output version information and exit

f) man - it is the interface used to view the system's reference manuals.


Syntax: man [-C file][-d][-D][--warnings[=warnings]]
g) cp - To copy one or more files to another location.

Syntax:
cp [options] … source destination
cp [options] … source ..directory

Description :
By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST
file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --
sparse=always to create a sparse DEST file whenever the SOURCE file contains a long enough
sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files.

Options:
Tag Description
-a, --archive same as –dpR
-b, --backup make backup before removal
-d, --no-dereference preserve links
-f, --force remove existing destinations, never prompt
-i, --interactive prompt before overwrite
-l, --link link files instead of copying
-p, --preserve preserve file attributes if possible
-P, --parents append source path to DIRECTORY
-r copy recursively, non-directories as files
--sparse=WHEN control creation of sparse files
-R, --recursive copy directories recursively
-s, --symbolic-link make symbolic links instead of copying
-S, --suffix=SUFFIX override the usual backup suffix
copy only when the SOURCE file is newer than the destination file or when
-u, --update
the destination file is missing
-v, --verbose explain what is being done
-V, --version-
override the usual version control
control=WORD
-x, --one-file-system stay on this file system
--help display this help and exit
--version output version information and exit.
Examples :
Copy sample.txt to sample.bak.
$ cat sample.txt
This is a sample file
$ cp sample.txt sample.bak
$ cat sample.bak
This is a sample file
Copy sample directory to home directory
$ cp -f /user/sample/* >

h) who - show who is logged on


Syntax :
who [OPTION]... [ FILE | ARG1 ARG2 ]
Options :
-a, --all same as -b -d --login -p -r -t -T -u
-b, --boot time of last system boot
-d, --dead print dead processes
-H, --heading
print line of column headings
-l, --login
print system login processes
--lookup
attempt to canonicalize hostnames via DNS
-m only hostname and user associated with stdin
-p, --process
print active processes spawned by init
-q, --count
all login names and number of users logged on
-r, --runlevel
print current runlevel
-s, --short
print only name, line, and time (default)
-t, --time print last system clock change

i) mv - move (rename) files


Syntax:
mv [OPTION]... [-T] SOURCE DEST
mv [OPTION]... SOURCE... DIRECTORY
mv [OPTION]... -t DIRECTORY SOURCE...

Options:
Tag Description
--backup[=CONTROL]
make a backup of each existing destination file
-b like --backup but does not accept an argument
-f, --force
do not prompt before overwriting
-i, --interactive
prompt before overwrite
--strip-trailing-slashes remove any trailing slashes from each SOURCE
argument
-S, --suffix=SUFFIX
override the usual backup suffix
-t, --target-directory=DIRECTORY
move all SOURCE arguments into DIRECTORY
-T, --no-target-directory
treat DEST as a normal file
-u, --update
move only when the SOURCE file is newer than the destination file or when
the destination file is missing
-v, --verbose
explain what is being done
--help display this help and exit
--version
output version information and exit

j) ls list directory contents.


Syntax:
ls [option] ….[file]

Description:

ls List information about the FILEs (the current directory by default). Sort entries alphabetically
if none of -cftuvSUX nor --sort is specified. Mandatory arguments to long options are
mandatory for short options too.

Options:

Tag Description
-a, --all do not ignore entries starting with .
-A, --almost-all do not list implied . and ..
--author with -l, print the author of each file
-b, --escape print octal escapes for nongraphic characters
--block-
use SIZE-byte blocks
size=SIZE
-B, --ignore-
do not list implied entries ending with ~
backups
with -lt: sort by, and show, ctime (time of last modification of file status
-c
information) with -l: show ctime and sort by name otherwise: sort by ctime
-C list entries by columns
control whether color is used to distinguish file types. WHEN may be
--color[=WHEN]
`never', `always', or `auto'
list directory entries instead of contents, and do not dereference symbolic
-d, --directory
links
-D, --dired generate output designed for Emacs' dired mode
-f do not sort, enable -aU, disable -ls --color

Example:
Example-1:
To list all files of current directory:
$ ls
output:
# ls
bin dev home lib lost+found mnt proc run srv tmp var
boot etc initrd.img lib64 media opt root sbin sys usr vmlinuz

k) mkdir - make directories

Syntax:
mkdir [OPTION] …DIRECTORY
.
Description:
Create the DIRECTORY(ies), if they do not already exist.
Mandatory arguments to long options are mandatory for short options too.
Options :
TAG DESCRIPTION
-m, --
set file mode (as in chmod), not a=rwx - umask
mode=MODE
-p, --parents no error if existing, make parent directories as needed
-v, --verbose print a message for each created directory
-Z, --
set the SELinux security context of each created directory to CTX
context=CTX
--help display this help and exit
--version output version information and exit
Adds args to the arguments appended on the kernel command line. If this is
--kernelargs args not specified mkbootdisk uses grubby to parse the arguments for the default
kernel from grub.conf, if possible.
Uses size (in kilobytes) as the size of the image to use for the boot disk. If this
--size size
is not specified, mkbootdisk will assume a standard 1.44Mb floppy device.

Examples:
Example-1:
Creates a new directory called mydir whose parent is the current directory.
$ mkdir mydir
output:
$ls
mydir
Example-2:
Create the mydir directory, and set its permissions such that all users may read, write, and
execute the contents.
$ mkdir -m a=rwx mydir
output:
# ls -l
total 24
-rw-r--r-- 1 ubuntu ubuntu 212 Jan 8 12:43 file.txt
drwxrwxrwx 2 root root 4096 Jan 8 15:27 mydir
Example-3:
How to create multiple directories at one time:
$ mkdir test1 test2 test3
output:
$ls
test1 test2 test3

l) rm remove files or directories


Syntax
rm [OPTION]... FILE...
Options:

TAG DESCRIPTION
-f, --force ignore nonexistent files, never prompt.
-i prompt before every removal.
prompt once before removing more than three files, or when removing
-I recursively. Less intrusive than -i, while still giving protection against
most mistakes.
-- prompt according to WHEN: never, once (-I), or always (-i). Without
interactive[=WHEN] WHEN, prompt always.
when removing a hierarchy recursively, skip any directory that is on a file
--one-file-system
system different from that of the corresponding command line argument.
--no-preserve-root do not treat '/' specially.
--preserve-root do not remove '/' (default).
-r, -R, --recursive remove directories and their contents recursively.
-v, --verbose explain what is being done.
--help display this help and exit.
--version output version information and exit.

Examples:
Example-1:
Remove the file myfile.txt. If the file is write-protected, you will be prompted to confirm that
you really want to delete it:
$ rm myfile.txt
Example-2:
Remove the file myfile.txt. You will not be prompted, even if the file is write-protected; if rm
can delete the file, it will:
$ rm -f myfile.txt
Example-3:
Remove all files in the working directory. If it is write-protected, you will be prompted before
rm removes it:
$ rm *

m) rmdir - remove empty directories

Syntax:
rmdir [OPTION]... DIRECTORY...

Description :
Remove the DIRECTORY(ies), if they are empty.

Options :
TAG DESCRIPTION
--ignore-fail-on-non-
ignore each failure that is solely because a directory is non-empty.
empty
remove DIRECTORY and its ancestors; e.g., 'rmdir -p a/b/c' is similar to
-p, --parents
'rmdir a/b/c a/b a'.
-v, --verbose output a diagnostic for every directory processed.
--help display this help and exit.
--version output version information and exit.

Examples :
Example-1:
rmdir command will delete the empty directories. i.e directory without any sub-directories or
files:
$ rmdir test
Example-2:
To Delete Nested Empty Directories in Linux:
$ rmdir -p dir1/dir2/dir3

n) echo - display a line of text.

Syntax : echo [SHORT-OPTION]... [STRING]...


echo LONG-OPTION

Description :
echo is a fundamental command found in most operating systems that offer a command line. It
is frequently used in scripts, batch files, and as part of individual commands; anywhere you may
need to insert text. Many command shells such as bash, ksh and csh implement echo as a built-
in command.

Options
Tag Description
-n Do not output a trailing newline.
Enable interpretation of backslash escape sequences (see below for a list
-e
of these).
-E Disable interpretation of backslash escape sequences (this is the default).
--help Display a help message and exit.
--version Output version information and exit.
\\ A literal backslash character ("\").
\a An alert (The BELL character).
\b Backspace
\c Produce no further output after this.
\e The escape character; equivalent to pressing the escape key.
\f A form feed.
\n A newline.
\r A carriage return
\t A horizontal tab.
\v A vertical tab.
\0NNN byte with octal value NNN (which can be 1 to 3 digits).
\xHH byte with hexadecimal value HH (which can be either 1 or 2 digits)

Examples :
Example-1:
To print string "Hello, World!" on console
$ echo "Hello, World!"
output:
Hello, World!
Example-2:
To print value of x, where x=10.
$ echo $x
output:
10

o) more - file perusal filter for crt viewing

Syntax :
more [-dlfpcsu] [-num] [+/ pattern] [+ linenum] []

Description:
More is a filter for paging through text one screenful at a time. This version is especially
primitive. Users should realize that less(1) provides more(1) emulation and extensive
enhancements.

Options:
Command line options are described below. Options are also taken from the environment
variable MORE (make sure to precede them with a dash (‘‘-’’)) but command line options will
override them.
Tag Description
-num
This option specifies an integer which is the screen size (in lines).
-d more will prompt the user with the message "[Press space to continue, ’q’ to
quit.]" and will display "[Press ’h’ for instructions.]" instead of ringing the
bell when an illegal key is pressed.
-l more usually treats ^L (form feed) as a special character, and will pause after
any line that contains a form feed. The -l option will prevent this behavior.
-f Causes more to count logical, rather than screen lines (i.e., long lines are not
folded).
-p Do not scroll. Instead, clear the whole screen and then display the text.
-c Do not scroll. Instead, paint each screen from the top, clearing the remainder
of each line as it is displayed.
-s Squeeze multiple blank lines into one.
-u Suppress underlining.
+/ The +/ option specifies a string that will be searched for before each file is
displayed.
+num Start at line number num.

p) date : date command is used to display system date and time.


Syntax:
date [OPTION]... [+FORMAT]
date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]]
Examples:
Example 1
$date
Output:
Tue Oct 10 22:55:01 PDT 2017

Example 2
$date -u
Output :
Wed Oct 11 06:11:31 UTC 2017

Example 3
$date --date="2/02/2010"
$date --date="Feb 2 2010"
Output:
Tue Feb 2 00:00:00 PST 2010
Tue Feb 2 00:00:00 PST 2010

q) history – history command is used to view the previously executed commands.


This feature was not available in the Bourne shell. Bash and Korn support this feature in which
every command executed is teated as the event as is associated with an event number using
which they can be recalled and change if required. These command are saved in a history file. In
bash sheel history command shows the whole list of the command.

Syntax:
$ history
q) chmod - To change owner, change the user and/or group ownership of each given File to a
new Owner. Chown can also change the ownership of a file to match the user/group of an
existing reference file.

Syntax: chown [Options]... NewOwner File...


chown [Options]... :Group File...
chown [Options]... --reference=RFILE File...

Description :
If used, NewOwner specifies the new owner and/or group as follows(with no embedded white
space):
chown [OWNER] [ [:.] [GROUP] ]
Following are the examples of how the owner/group can be specified:
• If only an OWNER (a user name or numeric user id) is given, that user is made the
owner of each given file, and the files' group is not changed.
chown OWNER
• If the OWNER is followed by a colon or dot and a GROUP (a group name or numeric
group id), with no spaces between them, the group ownership of the files is changed as
well (to GROUP).
• chown OWNER.GROUP
chown OWNER:GROUP
• If a colon or dot but no group name follows OWNER, that user is made the owner of the
files and the group of the files is changed to OWNER's login group.
• chown OWNER.
chown OWNER:
• If the colon or dot and following GROUP are given, but the owner is omitted, only the
group of the files is changed; in this case, 'chown' performs the same function as 'chgrp'.
• chown .GROUP
chown :GROUP

Options:
Tag Description
-c
Verbosely describe the action for each File whose ownership actually changes.
--changes
--dereference Do not act on symbolic links themselves but rather on what they point to.
-f
--silent Do not print error messages about files whose ownership cannot be changed.
--quiet
Act on symbolic links themselves instead of what they point to. This is the
default. This mode relies on the 'lchown' system call. On systems that do not
-h
provide the 'lchown' system call, 'chown' fails when a file specified on the
--no-dereference
command line is a symbolic link. By default, no diagnostic is issued for
symbolic links encountered during a recursive traversal, but see '--verbose'.
Use the user and group of the reference FILE instead of an explicit NewOwner
--reference=FILE
value.
-R
Recursively change ownership of directories and their contents.
--recursive
Verbosely describe the action (or non-action) taken for every FILE. If a
-v symbolic link is encountered during a recursive traversal on a system without
--verbose the 'lchown' system call, and '--no-dereference' is in effect, then issue a
diagnostic saying neither the symbolic link nor its referent is being changed.

Examples:

Change the owner of file.


$ chown user1 sample.txt
Change the group of file.
$ chown :mygroup file.txt
Change both the owner and group of file in single command.
$ chown user1:mygroup file.txt

r) pwd - print name of current/working directory


Print the full filename of the current working directory.
Tag Description
--help display this help and exit
--version
output version information and exit

s) wc - print the number of newlines, words, and bytes in files

Syntax : wc [OPTION]... [FILE]...

Options :
Print newline, word, and byte counts for each FILE, and a total line if more than one FILE is
specified. With no FILE, or when FILE is -, read standard input.
Tag Description
-c, --bytes
print the byte counts
-m, --chars
print the character counts
-l, --lines
print the newline counts
-L, --max-line-length
print the length of the longest line
-w, --words
print the word counts
--help display this help and exit
--version
output version information and exit

t) sort - sort lines of text files


Syntax :
sort [OPTION]... [FILE]...
Options:
Tag Description
-b, --ignore-leading-blanks
ignore leading blanks
-d, --dictionary-order
consider only blanks and alphanumeric characters
-f, --ignore-case
fold lower case to upper case characters
-g, --general-numeric-sort
compare according to general numerical value
-i, --ignore-nonprinting
consider only printable characters
-M, --month-sort
compare (unknown) < ‘JAN’ < ... < ‘DEC’
-n, --numeric-sort
compare according to string numerical value
-r, --reverse
reverse the result of comparisons

u) cut - To divide a file into several parts (columns)


Syntax :
cut [OPTION]...[FILE]...
Options:
Tag Description
Print only the bytes in positions listed in BYTE-LIST. Tabs and
-b BYTE-LIST
backspaces are treated like any other character; they take up 1
--bytes=BYTE-LIST
byte.
Print only characters in positions listed in CHARACTER-LIST.
-c CHARACTER-LIST The same as '-b' for now, but internationalization will change
--characters=CHARACTER-LIST that. Tabs and backspaces are treated like any other character;
they take up 1 character.
-f FIELD-LIST Print only the fields listed in FIELD-LIST. Fields are separated
--fields=FIELD-LIST by a TAB character by default.
-d INPUT_DELIM_BYTE For '-f', fields are separated in the input by the first character in
--delimiter=INPUT_DELIM_BYTE INPUT_DELIM_BYTE (default is TAB).
-n Do not split multi-byte characters (no-op for now).
-s For '-f', do not print lines that do not contain the field separator
--only-delimited character.
For '-f', output fields are separated by
--output-
OUTPUT_DELIM_STRING The default is to use the input
delimiter=OUTPUT_DELIM_STRING
delimiter.
Examples:
Let's have a sample file sample.txt
$ cat sample.txt
1;2;3;4;5;6;7;8;9
To Parse out column 2 from a semicolon (;) delimited file:
$ cat sample.txt | cut -d \; -f 2 > output.txt
$ cat output.txt
2

v) paste : merge lines of files


Syntax :
paste [OPTION]... [FILE]..
Options:
Tag Description
-d, --delimiters=LIST
reuse characters from LIST instead of TABs
-s, --serial
paste one file at a time instead of in parallel
--help display this help and exit
--version
output version information and exit

w) logout - session-logout.
Syntax:
session-logout[options]
Description:logout command allows you to programmatically logout from your session. causes
the session manager to take the requested action immediately.

Examples:
Example-1:
To logout from current user session:
$ logout
output:
no output on screen, current user session will be logged out.

x) shutdown - bring the system down


Options:
Tag Description
-a Use /etc/shutdown.allow.
-t sec Tell init(8) to wait sec seconds between sending processes the warning and
the kill signal, before changing to another runlevel.
-k Don’t really shutdown; only send the warning messages to everybody.
-r Reboot after shutdown.
-h Halt or poweroff after shutdown.
-H Halt action is to halt or drop into boot monitor on systems that support it.
-P Halt action is to turn off the power.
-n [DEPRECATED] Don’t call init(8) to do the shutdown but do it ourself. The
use of this option is discouraged, and its results are not always what you’d
expect.
-f Skip fsck on reboot.
-F Force fsck on reboot.
-c Cancel an already running shutdown. With this option it is of course not
possible to give the time argument, but you can enter a explanatory message
on the command line that will be sent to all users.
Time When to shutdown.
warning-message Message to send to all users.
Objective:

2. Demonstration of VI editor
Session-1
a) Use vi editor to create a file called myfile.txt which contains some text.
b) Correct typing errors during creation.
c) Save the file
d) Logout of the system

Session-2
a) Log into the system
b) Open the file created in session 1
c) Add some text
d) Change some text
e) Delete some text
f) Save the Changes
g) Logout of the system

Session-1

Procedure:

a)Log into the system


Output : Login
b)Use vi editor to create a file called myfile.txt which contains some text. Output : vi
mytable
c)correct typing errors during creation.
Output : Practice vi editor commands\
d)Save the file
Output : Esc : wq Enter
e)logout of the system
Output : logout

To Enter VI Editor:

To Start vi

To use vi on a file, type in vi filename. If the file named filename exists, then the first
page (or screen) of the file will be displayed; if the file does not exist, then an empty file
and screen are created into which you may enter text.

• vi filename edit filename starting at line 1


• vi –r filename recover filename that was being edited when system crashed

To Exit vi
Usually the new or modified file is saved when you leave vi. However, it is also possible
to quit vi without saving the file.

Note: The cursor moves to bottom of screen whenever a colon (:) is typed. Thistype of
command is completed by hitting the <Return> (or <Enter>) key.

:x quit vi, writing out modified file to file named in original invocation
:wq quit vi, writing out modified file to file named in original invocation
:q quit (or exit) vi

:q! quit vi even though latest changes have not been saved for this vi call

Session-2

Procedure:

a)Log into the system


b)open the file created in session 1
c)Add some text
d)Change some text
e)Delete some text
f)Save the Changes
Output : Practice the commands in Vi editor
g)Logout of the system

Note… Make Use of following commands

c)Inserting or Adding Text

The following commands allow you to insert and add text. Each of these commands puts the vi
editor into insert mode; thus, the <Esc> key must be pressed to terminate the entry of text and to
put the vi editor back into command mode.

i insert text before cursor, until <Esc> hit


I insert text at beginning of current line, until <Esc> hit
a append text after cursor, until <Esc> hit
A append text to end of current line, until <Esc> hit
o open and put text in a new line below current line, until <Esc> hit
O open and put text in a new line above current line, until <Esc> hit
E)Deleting Text
r replace single character under cursor (no <Esc> needed)
R replace characters, starting with current cursor position, until <Esc> hit
change the current word with new text,starting with the character under cursor, until
cw
<Esc> hit
change N words beginning with character under cursor, until <Esc> hit; e.g., c5w
cNw
changes 5 words
C change (replace) the characters in the current line, until <Esc> hit
cc change (replace) the entire current line, stopping when <Esc> is hit

The following commands allow you to delete text.

x delete single character under cursor


Nx delete N characters, starting with character under cursor
dw delete the single word beginning with character under cursor
dNw delete N words beginning with character under cursor; e.g., d5w deletes 5 words
D delete the remainder of the line,starting with current cursor position
dd delete entire current line
Ndd or
delete N lines, beginning with the current line;
dNd
e.g., 5dd deletes 5 lines
3. a) Write a shell script to generate the mathematical tables.
b) Write a shell script to find the factorial of a given number.
c) Write a shell script that computes the gross salary of a employee according to the
following rules:
i) If basic salary is < 1500 then HRA =10% of the basic and DA =90% of the basic.
ii) If basic salary is >=1500 then HRA =Rs500 and DA=98% of the basic

Procedure:

1.Read a number
2.using iter variable it will initialize the value
3.check the condition using while
4.calculate the result and display the result using echo
5.increment the iter value

Source code:

echo "Which table do you want ? (Give Number):"


read num
echo “----Multiplication Table of $num------”
iter=1
while [ $iter -le 10 ]
do
res=`expr $num \* $iter`
echo "$num * $iter = $res"
iter=`expr $iter + 1`
done

OUTPUT: $ sh 13_26.sh
Which table do you want ? (Give Number):
4
----Multiplication Table of 4------
4*1=4
4*2=8
4 * 3 = 12
4 * 4 = 16
4 * 5 = 20
4 * 6 = 24
4 * 7 = 28
4 * 8 = 32
4 * 9 = 36
4 * 10 = 40
b)
Procedure:

1.Initialize a fact value


2.using for loopdo the iteration until the condition satisfy.
3.calculate the fact and display the result using echo statement

Source Code:

for i in $*
do
fact=1
for((j = 1 ; j <= $i ; j++))
do
fact=`expr $fact \* $j`
done
echo " $i! =”$fact"
done
Output:$ sh fact.sh 3 6 2 5
3! = 6
6! = 720
2! = 2
5! = 120

c)

Procedure:

1.Read the bsal


2.check the bsal < 1500 then calculate gsal
3.Display the result
4.check the bsal >1500 then calculate gsal
5..Display the result

Source code: $ vi gsalary.sh

echo "ENTER THE BASIC SALARY"


read bsal
if test $bsal -lt 1500
then
gsal=$((bsal+((bsal/100)*10)+(bsal/100)*90))
echo "the gross salary:$gsal"
fi
if test $bsal -ge 1500
then
gsal=$(((bsal+500)+(bsal/100)*98))
echo "the gross salary:$gsal"
fi
Output: $ sh gsal.sh
1) ENTER THE BASIC SALARY
1200
the gross salary:2400
2) ENTER THE BASIC SALARY
2400
the gross salary:5252
4. a) Write a shell script (small calculator) that adds, subtracts, multiplies and divides the
two given numbers. There are two division options: one returns the quotient and the other
remainder. The script requires three arguments: the operation to be used and the two
integers. The operation is specified by options:
Add -a
Subtract-s
Multiply -m
Quotient -c
Remainder –r
b) Write a shell script to accept student number, name, and marks in five subjects. Find
total, average and grade.
Rules:
Avg>=80 then grade A
Avg<80&&Avg>=70 then grade B
Avg<70&&Avg>=60 then grade C
Avg<60&&Avg>=50 then grade D
Avg<50&&Avg>=40 then grade E
Else grade F

a)
Procedure:

1.Read the input values from keyboard


2.Enter the switch case number
3.Calculate the result using “expr” statement
4.Display the result

Source Code
echo "Enter First Value "
read x
echo "Enter Second Value "
read y
while [$q –ne 0 ]
do
echo “Enter –a for adding”
echo “Enter –s for subtraction”
echo “Enter –m for multiplication”
echo “Enter –c for Quotient”
echo “Enter –r for reminder”
read s
case $s in
-a) p=`expr $x + $y`
Echo "Sum = $p"
;;
-b) p=`expr $x - $y`
Echo "difference = $p"
;;
-m) p=`expr $x \* $y`
Echo "Product = $p"
;;
-c) p=`expr $x / $y`
Echo "quotient = $p"
;;
-r) p=`expr $x % $y`
Echo “reminder = $p"
;;

b)
Procedure:

1.Read the input values from keyboard


2.Add five subject marks using while loop
3.Calculate the total and average of the subjects
4.Display the grades of students using if conditions

Source code:

echo "enter the student name:"


read sname
echo "enter the student roll no:"
read sno
echo "enter the no of subjects "
read n
i=1
while [ $i -le $n ]
do
echo "enter subject$i marks:"
read a[$i]
i=`expr $i + 1`
done
i=1
total=0
while [ $i -le $n ]
do
total=`expr $total + ${a[i]}`
i=`expr $i + 1`
done
echo "totalis :"$total > stu.dat
average=`expr $total / $n`
echo "average is:"$average >> stu.dat
if [ $average -ge 80 ]
then
echo "student grade is A " >> stu.dat
elif [ $average -lt 80 -a $average -ge 70 ]
then
echo "student grade is B " >> stu.dat
elif [ $average -lt 70 -a $average -ge 60 ]
then
echo "student grade is C" >> stu.dat
elif [ $average -lt 60 -a $average -ge 50 ]
then
echo "student grade is D" >> stu.dat
elif [ $average -lt 50 -a $average -ge 40 ]
then
echo "student grade is E" >> stu.dat
else
echo "student grade is F " >> stu.dat
fi
Output:$ sh grade.sh
enter the student name:
abc
enter the student roll no:
01
enter the no of subjects
5
enter subject1 marks:
10
enter subject2 marks:
20
enter subject3 marks:
30
enter subject4 marks:
40
enter subject5 marks:
50
$ cat stu.dat
Totalis :150
Average is 30
Student grade is F

c)
Procedure:

1.Read the input values from keyboard


2.using while loop calculate the gcd value
3.Display the gcd of two numbers
echo Enter two numbers with space in between

// read for scanning


read a b

// Assigning the value of a to m


m = $a

// Condition checking if b greater than m


// If yes the replace the value of m assign a new value
if [ $b -lt $m ]
then
m = $b
fi

// In do while loop we are checking the gcd


while [ $m -ne 0 ]
do
x = `expr $a % $m`
y = `expr $b % $m`

// If x and y both are 0 then we complete over


// process and we print the gcd
if [ $x -eq 0 -a $y -eq 0 ]
then

// Printing the greatest gcd of two given number


echo gcd of $a and $b is $m
break
fi
m = `expr $m - 1`

done

Input
25 15
Output
5
5. a) Write a shell script to display string palindrome from given arguments.
b) Write a shell script which will display Armstrong numbers from given arguments.
c) Write a shell script to display reverse numbers from given argument list.

a)
Procedure:

1.Read the input string from keyboard


2.calculate the length of the string
3.reverse the string using the while loop.
4.check the orginal string and reverse string are equal then display palindrome
5.Else Not a palindrome

for i in $*
do
l=`expr length $i`
c=0
while [ $c -le $l ]
do
e=`expr substr $i $l 1`
p=$p$e
l=`expr $l - 1`
done
if [ $p = $i ]
then
echo "The given string $i is a palindrome"
else
echo "The given string $i is not a palindrome"
fi
p=""
done

OUTPUT: $ sh palin.sh madam hai Malayalam


The given string madam is a palindrome
The given string hai is not a palindrome
The given string malayalam is a palindrome

b. Write a shell script which will display Armstrong numbers from given arguments.

Procedure:

1.Read the input


2.store the input in a temporary variable.
3.calculate the original value using while loop and put in a variable
4.check the orginal value and temporary variable are equal print the number is amstrong
number
5.Else Not a amstrong number

for i in $*
do
s=0
t=$i
k=$i
while [ $i -gt 0 ]
do
r=`expr $i % 10`
s=`expr $s + $r \* $r \* $r`
i=`expr $i / 10`
done
if [ $s -eq $t ]
then
echo "$t is an armstrong number"
else
echo "$t is not an armstrong number"
fi
done

OUTPUT: $ sh arm.sh 153 123 370 371 407


153 is an armstrong number
123 is not an armstrong number
370 is an armstrong number
371 is an armstrong number
407 is an armstrong number

c.

Objective:
Write a shell script to display reverse numbers from given argument list.

Procedure:

1.Read the input


2.store the input in a temporary variable.
3.calculate the original value using while loop and put in a variable
4. print the reverse number
Source Code:

for i in $*
do
t=$i
s=0
while [ $i -gt 0 ]
do
r=`expr $i % 10`
s=`expr $r + $s \* 10`
i=`expr $i / 10`
done
echo "Reverse of $t is $s"
done

OUTPUT: $ sh rev.sh 123 345 6458


Reverse of 123 is 321
Reverse of 345 is 543
Reverse of 6458 is 8546
6. a) Write a shell script to find largest element in a array
b) Write a shell script to determine whether a given number is a prime number or not.
c) Write a shell script to generate a Floyd triangle for a given value.

a)
Procedure:

1.Read the input array


2.store the first element of array in a biggest variable.
3.check the i value is greater than biggest variable then replace the I value in biggest
variable
4. iterate the loop
5.display the largest number.

echo "Enter the elements into array"


read -a integers
biggest=${integers[0]}
smallest=${integers[0]}
for i in ${integers[@]}
do
if [[ $i -gt $biggest ]]
then
biggest="$i"
fi
done
echo "The largest number is $biggest"

OUTPUT: $ sh maxele.sh
Enter the elements into array
110 58 244 14 558 4411 774
The largest number is 4411

b)
Procedure:

1.Read the input


2.using prime function check whether given number is prime or not .
3.Display the result

Source Code:
echo "enter number"
read num
function prime
{
for((i=2; i<=num/2; i++))
do
if [ $((num%i)) -eq 0 ]
then
echo "$num is not a prime number."
exit
fi
done
echo "$num is a prime number."
}
r=`prime $number`
echo "$r"

Output:
$ ./ prime.sh
Enter number
4
4 is not prime number

$./ prim.sh
Enter number
7
7 is a prime number

c)
Procedure:

1.Read the input


2.using for loop iterate rows and values of a triangle .
3.Display the Floyd triangle.

number=1
rows=4
for((i=1; i<=rows; i++))
do
for((j=1; j<=i; j++))
do
echo -n "$number "
number=$((number + 1))
done
echo
done

1
23
456
7 8 9 10
7. a) Write a shell script to print all the primes below a given number is a prime number.
b) Write a shell script to print the first ‘n’ Fibonacci numbers.
c) Write a shell script which displays the list of all files in a given directory.

a)
Procedure:

1.Read the input range


2.using while loop calculate the prime values.
3.Display the prime numbers from the given range.

Source Code
echo "enter the range"
read n
echo "the prime no are:"
m=2
while [ $m -le $n ] do
i=2 flag=0
while [ $i -le `expr $m / 2` ] do
if [ `expr $m % $i` -eq 0 ] then
flag=1 break fi
i=`expr $i + 1`
done
if [ $flag -eq 0 ]
then echo $m fi
m=`expr $m + 1`
done

Output:
Enter the range
10
The prime no are 2
3
5
7

b)
Procedure:

1.Read the input


2.using function fib calculate the Fibonacci values
3.Stores the value in r variable
4.Display the result

SourceCode:
echo "How many number of terms to be generated ?"
read n
function fib
{
x=0
y=1
i=2
echo "Fibonacci Series up to $n terms :"
echo "$x"
echo "$y"
while [ $i -lt $n ]
do
i=`expr $i + 1 `
z=`expr $x + $y `
echo "$z"
x=$y
y=$z
done
}
r=`fib $n`
echo "$r"
Output:
How many numbers of terms to be generated?
5
Fibonacci series upto 5 terms are
0
1
1
2
3

c)
Procedure:

1.Read the directory name as input


2.check the -d then display the files the list of files in a directory
3.using the while loop check the file having all the permissions
4.Display the result
5.Else not having permissions

SourceCode:
echo "enter the directory name"
read dir
if [ -d $dir ]
then
cd $dir
ls > f
exec < f
while read line
do if [ -f $line ]
then
if [ -r $line -a -w $line -a -x $line ]
then
echo "$line has all permissions"
else
echo "files not having all permissions"
fi
fi
done
fi

Output:
Enter the directory name : dir
File1, File 2 has all permissions
File 3 not having all permissions
8. a) Write a shell script to sort elements of given array by using selection sort.
b) Write a shell script to search given number using binary search.

a) Procedure:

1.Read the input


2.using for loop check the elements in array
3.Swap the elements in array
4.Display the result

SourceCode:

Echo “enter the number”


Read n
Echo “enter numbers in the array”
For((i=0;i<n;i++))
Do
Read arr[$i]
Done
#logic for selection sort
For((i=0;i<n-1;i++))
Do
Small=${arr[$i]}
Index=$i
For((j=i+1;j<n;j++))
Do
If((arr[j]<small))
Then
Small=${arr[$j]}
Index=$j
Fi
Done
Temp=${arr[$i]}
Arr[$i]=${arr[$index]}
Arr[$index]=$temp
Done
#printing sorted array
Echo “printing sorted array”
For((i=0;i<n;i++))
Do
Echo ${arr[$i]}
Done
Output:
Enter the number : 5
Enter numbers in the array:
27813
Printing Sorted array
1
2
3
7
8

b)

Procedure:

1.Read the input


2.using for loop check the elements in array
3.Swap the elements in array and put in sorted manner
4.Enter the element to be searched and
5.Display the position and element in a given array

Echo “Enter the limit:”


Read n
Echo “Enter the numbers”
For(( i=0 ;i<n; i++ ))
Do
Read m
A[i]=$m
Done
For(( i=1; i<n; i++ ))
Do
For(( j=0; j<n-I; j++))
Do
If [ ${a[$j]} -gt ${a[$j+1]} ]
Then
T=${a[$j]}
A[$j]=${a[$j+1]}
A[$j+1]=$t
Fi
Done
Done
Echo “Sorted array is”
For(( i=0; i<n; i++ ))
Do
Echo “${a[$i]}”
Done
Echo “Enter the element to be searched :”
Read s
L=0
C=0
U=$(($n-1))
While [ $l -le $u ]
Do
Mid=$(((( $l+$u ))/2 ))
If [ $s -eq ${a[$mid]} ]
Then
C=1
Break
Elif [ $s -lt ${a[$mid]} ]
Then
U=$(($mid-1))
Else
L=$(($mid+1))
Fi
Done
If [ $c -eq 1 ]
Then
Echo “Element found at position $(($mid+1))”
Else
Echo “Element not found”
Fi

Output:
Enter the limit: 5
Enter the numbers
42637
Sorted array is
23467
Enter the number to be searched :7
Element found in position 5
9. a) Write a sed command that deletes the first character in each line in a file.
b) Write a sed command that deletes the character before the last character in each line in
afile.

a)
Procedure:

1.create input file


2.Read the input file using sed command
3.display the result that deletes first character.

SourceCode:
sed 's/^./ /‟ file1.dat

Output:
Unix is Multiuser OS
Unix was developed by Brian Kernighan and KenThomson

b)Write a sed command that deletes the last character in each line in a file.

Procedure:

1.create a input file


2.Read the input file using sed command
2.display the result that deletes last before character.

SourceCode

sed '$s/.$//' file1.dat

Output:

Unix is Multiuser O
Unix was developed by Brian Kernighan and KenThomso
10. a) Write an awk program to print sum, avg of students marks list
b) Write an awk program to display students pass/fail report.
c) Write an awk program to count the no. of vowels in a given file.

a)
Procedure:

1.create a input file


2.Read the input file and calculate sum,average of marks in a list
3display the result.

SourceCode:

BEGIN{total=0;avg=0;
print"Name Grp S1 S2 S3 S4 S5\tTotal AVerage Result"
print"------- --- -- -- -- -- --\t ----- ---------- ------"}
{
total=$3+$4+$5+$6+$7;
avg=total/5;
if($3>35 && $4>35 && $5>35 && $6>35 && $7>35)
{
{print $0 "\t" total "\t" avg "\t" "PASS" }
}
else
{
{print $0 "\t" total "\t" avg "\t" "Fail" }
}}
END{}
$ cat student.data
Pavan MSC 55 66 77 88 99
kumar MSC 65 48 75 95 75
Raju MSC 78 95 78 35 78
Bala MSC 85 48 55 95 75
chakri MSC 51 25 48 35 39
Output:
$ awk -f lab14.awk student.data
Name Grp S1 S2 S3 S4 S5 Total Average Result
------ ---- -- -- -- -- -- ----- ----------- --------
Pavan MSC 55 66 77 88 99 385 77 PASS
kumar MSC 65 48 75 95 75 358 71.6 PASS
Raju MSC 78 95 78 35 78 364 72.8 Fail
Bala MSC 85 48 55 95 75 358 71.6 PASS
Chakri MSC 51 25 48 35 39 198 39.6 Fail
b)
Procedure:

1.create a input file


2.Read the input file and calculate sum,average of marks in a list
3display the pass/fail report

Source Code
BEGIN{total=0;avg=0;
print"Name Grp S1 S2 S3 S4 S5\tTotal AVerage Result"
print"------- --- -- -- -- -- --\t ----- ---------- ------"}
{
total=$3+$4+$5+$6+$7;
avg=total/5;
if($3>35 && $4>35 && $5>35 && $6>35 && $7>35)
{{print $0 "\t" total "\t" avg "\t" "PASS" }}
else
{
{print $0 "\t" total "\t" avg "\t" "Fail" }
}}
END{}
$ cat student.data
Pavan MSC 55 66 77 88 99
kumar MSC 65 48 75 95 75
Raju MSC 78 95 78 35 78
Bala MSC 85 48 55 95 75
chakri MSC 51 25 48 35 39

Output:
$ awk -f lab14.awk student.data
Name Grp S1 S2 S3 S4 S5 Total Average Result
------ ---- -- -- -- -- -- ----- ----------- --------
Pavan MSC 55 66 77 88 99 385 77 PASS
kumar MSC 65 48 75 95 75 358 71.6 PASS
Raju MSC 78 95 78 35 78 364 72.8 Fail
Bala MSC 85 48 55 95 75 358 71.6 PASS
Chakri MSC 51 25 48 35 39 198 39.6 Fail

c)
Procedure:

1.Read the input file and find out vowels in that file
3display the result.
SourceCode:
echo "I have a dog" | perl -lne'
$x = "\L$_";
map{ print "$_-", $x =~ s/$_//g||0 } qw(a e i o u)

Output:
a-2
e-1
i-1
o-1
u-0

You might also like