OS Lab Manual

41
PROGRAM NO. 1 LINUX OPERATING SYSTEM Linux is a generic term referring to Unix-like computer operating systems based on the Linux kernel. Their development is one of the most prominent examples of free and open source software collaboration; typically all the underlying source code can be used, freely modified, and redistributed, both commercially and non-commercially, by anyone under licenses such as the GNU General Public License. Linux can be installed on a wide variety of computer hardware, ranging from embedded devices such as mobile phones, smartphones and wristwatches to mainframes and supercomputers. Linux is predominantly known for its use in servers; in 2007 Linux's overall share of the server market was estimated at 12.7%, while a 2008 estimate suggested that 60% of all web servers ran Linux. Most desktop computers run either Mac OS X or Microsoft Windows, with Linux having only 1–2% of the desktop market. However, desktop use of Linux has become increasingly popular in recent years, partly owing to the popular Ubuntu distribution and the emergence of netbooks and smartbooks. Typically Linux is packaged in a format known as a Linux distribution for desktop and server use. Linux distributions include the Linux kernel and all of the supporting software required to run a complete system, such as utilities and libraries, the X Window System, the GNOME and KDE desktop environments, and the Apache HTTP Server. Commonly-used applications with desktop Linux systems include the Mozilla Firefox web-browser and the OpenOffice.org office application suite. The name "Linux" comes from the Linux kernel, originally written in 1991 by Linus Torvalds. The contribution of a supporting Userland in the form of system tools and libraries from the GNU Project (announced in 1983 by Richard Stallman) is the basis for the Free Software Foundation's preferred name GNU/Linux.

Transcript of OS Lab Manual

Page 1: OS Lab Manual

PROGRAM NO. 1

LINUX OPERATING SYSTEM

Linux is a generic term referring to Unix-like computer operating systems based on the Linux kernel. Their development is one of the most prominent examples of free and open source software collaboration; typically all the underlying source code can be used, freely modified, and redistributed, both commercially and non-commercially, by anyone under licenses such as the GNU General Public License.Linux can be installed on a wide variety of computer hardware, ranging from embedded devices such as mobile phones, smartphones and wristwatches to mainframes and supercomputers. Linux is predominantly known for its use in servers; in 2007 Linux's overall share of the server market was estimated at 12.7%, while a 2008 estimate suggested that 60% of all web servers ran Linux. Most desktop computers run either Mac OS X or Microsoft Windows, with Linux having only 1–2% of the desktop market. However, desktop use of Linux has become increasingly popular in recent years, partly owing to the popular Ubuntu distribution and the emergence of netbooks and smartbooks. Typically Linux is packaged in a format known as a Linux distribution for desktop and server use. Linux distributions include the Linux kernel and all of the supporting software required to run a complete system, such as utilities and libraries, the X Window System, the GNOME and KDE desktop environments, and the Apache HTTP Server. Commonly-used applications with desktop Linux systems include the Mozilla Firefox web-browser and the OpenOffice.org office application suite.The name "Linux" comes from the Linux kernel, originally written in 1991 by Linus Torvalds. The contribution of a supporting Userland in the form of system tools and libraries from the GNU Project (announced in 1983 by Richard Stallman) is the basis for the Free Software Foundation's preferred name GNU/Linux.

ArchitectureLinux is a monolithic kernel. Device drivers and kernel extensions run in kernel space (ring 0 in many CPU architectures), with full access to the hardware, although some exceptions run in user space. The graphics system most people use with Linux doesn't run in the kernel, in contrast to that found in Microsoft Windows.Kernel mode preemption allows device drivers to be preempted under certain conditions. This feature was added to handle hardware interrupts correctly and improve support for symmetric multiprocessing (SMP). Preemption also improves latency, increasing responsiveness and making Linux more suitable for real-time applications.

Page 2: OS Lab Manual

Kernel panicIn Linux, a "panic" is an unrecoverable system error detected by the kernel as opposed to similar errors detected by user space code. It is possible for kernel code to indicate such a condition by calling the panic function located in the header file sys/system.h. However, most panics are the result of unhandled processor exceptions in kernel code, such as references to invalid memory addresses. These are typically indicative of a bug somewhere in the call chain leading to the panic. They can also indicate a failure of hardware, such as a failed RAM cell or errors in arithmetic functions in the processor caused by a processor bug, overheating/damaged processor, or a soft error.

Programming languagesLinux is written in the version of the C programming language supported by GCC (which has introduced a number of extensions and changes to standard C), together with a number of short sections of code written in the assembly language (in GCC's "AT&T-style" syntax) of the target architecture. Because of the extensions to C it supports, GCC was for a long time the only compiler capable of correctly building Linux. In 2004, Intel claimed to have modified the kernel so that its C compiler also was capable of compiling it. There was another such reported success in 2009 with a modified 2.6.22. Many other languages are used in some way, primarily in connection with the kernel build process (the methods whereby the bootable image is created from the sources). These include Perl, Python, and various shell scripting languages. Some drivers may also be written in C++, Fortran, or other languages, but this is strongly discouraged. Linux's build system only officially supports GCC as a kernel and driver compiler.

PortabilityWhile not originally designed to be portable, Linux is now one of the most widely ported operating system kernels, running on a diverse range of systems from the iPAQ (a handheld computer) to the IBM System z9 (a massive mainframe server that can run hundreds or even thousands of concurrent Linux instances). Linux runs as the main operating system on IBM's Blue Gene supercomputers. As of June 2009, Linux is the OS on more than 88% of systems on the Top 500 supercomputers list. Also, Linux has been ported to various handheld devices such as TuxPhone and Apple's iPod. The Android operating system, developed for mobile phone devices, uses a modified version of the Linux kernel.

Page 3: OS Lab Manual

Virtual machine architecturesThe Linux kernel has extensive support for and runs on many virtual machine architectures both as the host operating system and as a client operating system. The virtual machines usually emulate Intel x 86 families of processors, though in a few cases PowerPC or AMD processors are also emulated.

Features of linux Multitasking: several programs running at the same time. Multiuser: several users on the same machine at the same time (and no two-

user licenses!). Multiplatform: runs on many different CPUs, not just Intel. Multiprocessor, Multithreading: has native kernel support for multiple independent threads of

control within a single process memory space. Has memory protection between processes, so that one program can't bring the

whole system down. Demand loads executables: Linux only reads from disk those parts of a

program that are actually used. Shared copy-on-write pages among executables. This means that multiple

process can use the same memory to run in. When one tries to write to that memory, that page (4KB piece of memory) is copied somewhere else. Copy-on-write has two benefits: increasing speed and decreasing memory use.

Virtual memory using paging (not swapping whole processes) to disk: to a separate partition or a file in the file system, or both, with the possibility of adding more swapping areas during runtime (yes, they're still called swapping areas). A total of 16 of these 128 MB (2GB in recent kernels) swapping areas can be used at the same time, for a theoretical total of 2 GB of useable swap space. It is simple to increase this if necessary, by changing a few lines of source code.

A unified memory pool for user programs and disk cache, so that all free memory can be used for caching, and the cache can be reduced when running large programs.

Mostly compatible with POSIX, System V, and BSD at the source level. All source code is available, including the whole kernel and all drivers, the

development tools and all user programs; also, all of it is freely distributable. Plenty of commercial programs are being provided for Linux without source, but everything that has been free, including the entire base operating system, is still free.

Supports several common file systems, including minix, Xenix, and all the common system V file systems, and has an advanced file system of its own, which offers file systems of up to 4 TB, and names up to 255 characters long.

Advantages

1. Low cost: You don’t need to spend time and money to obtain licenses since Linux and much of its software come with the GNU General Public License. You can start to work immediately without worrying that your software may stop working anytime because the free trial version expires. Additionally, there are large repositories from which you can freely download high quality software for almost any task you can think of.

Page 4: OS Lab Manual

2. Stability: Linux doesn’t need to be rebooted periodically to maintain performance levels. It doesn’t freeze up or slow down over time due to memory leaks and such. Continuous up-times of hundreds of days (up to a year or more) are not uncommon.

3. Performance: Linux provides persistent high performance on workstations and on networks. It can handle unusually large numbers of users simultaneously, and can make old computers sufficiently responsive to be useful again.

4. Network friendliness: Linux was developed by a group of programmers over the Internet and has therefore strong support for network functionality; client and server systems can be easily set up on any computer running Linux. It can perform tasks such as network backups faster and more reliably than alternative systems.

5. Flexibility: Linux can be used for high performance server applications, desktop applications, and embedded systems. You can save disk space by only installing the components needed for a particular use. You can restrict the use of specific computers by installing for example only selected office applications instead of the whole suite.

6. Compatibility: It runs all common Unix software packages and can process all common file formats.

7. Choice: The large number of Linux distributions gives you a choice. Each distribution is developed and supported by a different organization. You can pick the one you like best; the core functionalities are the same; most software runs on most distributions.

8. Fast and easy installation: Most Linux distributions come with user-friendly installation and setup programs. Popular Linux distributions come with tools that make installation of additional software very user friendly as well.

9. Full use of hard disk: Linux continues work well even when the hard disk is almost full.

10. Multitasking: Linux is designed to do many things at the same time; e.g., a large printing job in the background won’t slow down your other work.

11. Security: Linux is one of the most secure operating systems. “Walls” and flexible file access permission systems prevent access by unwanted visitors or viruses. Linux users have to option to select and safely download software, free of charge, from online repositories containing thousands of high quality packages. No purchase transactions requiring credit card numbers or other sensitive personal information are necessary.

12. Open Source: If you develop software that requires knowledge or modification of the operating system code, Linux’s source code is at your fingertips. Most Linux applications are Open Source as well.

Disadvantages

Because you must learn unix commands, it takes longer to learn about linux. Printed instruction manuals and technical support is much harder to find. Configuring devices in linux is generally more difficult.

Page 5: OS Lab Manual

Linux does not have an abundance of commercial software such as, word-processing software, internet explorer and games.

The linux GUI does not provide as much functionality as the linux CLI (command line interface).

PROGRAM – 2

TO STUDY WINDOWS 2000 OPERATING SYSTEM

Windows 2000 is a line of operating systems produced by Microsoft for use on business desktops, notebook computers, and servers. Released on 17 February 2000, it

Page 6: OS Lab Manual

was the successor to Windows NT 4.0, and is the final release of Microsoft Windows to display the "Windows NT" designation. It was succeeded by Windows XP for desktop systems in October 2001 and Windows Server 2003 for servers in April 2003.

Four editions of Windows 2000 were released: Professional, Server, Advanced Server, and Datacenter Server. Additionally, Microsoft sold Windows 2000 Advanced Server Limited Edition and Windows 2000 Datacenter Server Limited Edition, which were released in 2001 and run on 64-bit Intel Itanium microprocessors. While each edition of Windows 2000 was targeted to a different market, they share a core set of features, including many system utilities such as the Microsoft Management Console and standard system administration applications. Support for people with disabilities has been improved over Windows NT 4.0 with a number of new assistive technologies, and Microsoft increased support for different languages and locale information. All versions of the operating system support the Windows NT file system, NTFS 3.0, the Encrypting File System, as well as basic and dynamic disk storage. The Windows 2000 Server family has additional features, including the ability to provide Active Directory services (a hierarchical framework of resources), Distributed File System (a file system that supports sharing of files) and fault-redundant storage volumes. Windows 2000 can be installed through either a manual or unattended installation. Unattended installations rely on the use of answer files to fill in installation information, and can be performed through a bootable CD using Microsoft Systems Management Server, by the System Preparation Tool. Microsoft marketed Windows 2000 as the most secure Windows version ever, but it became the target of a number of high-profile virus attacks such as Code Red and Nimda. Over ten years after its release, it continues to receive patches for security vulnerabilities nearly every month and will continue to do so until 13 July 2010.

Features of Windows 20001. Setup Manager: Setup Manager provides a graphic interface to the users to

make installation scripts.2. Faster Multitasking: It allows user to run multiple programs and perform

different tasks such as browsing, listening music, downloading and working on the files at the same time.

3. Troubleshooters: It assists users to troubleshoot, optimize and configure a lot of functionalities of Windows 2000 Professional, which results in greater performance and greater productivity.

4. Personalized Menu: It adapts the start menu to show the applications that you most work on.

5. Encrypting File System: With EFS each file can be encrypted with the randomly generated key. The encryption and decryption features provide a security layer to the files and folders.

6. IP Security Support: IPSEC is a security protocol that protects the data over the network. In Virtual Private Networks, IPSEC plays an important role in securely transmitting the data to the remote location through internet.

7. Microsoft Management Console: MMC provides centralized environment for the management tools and you can access MMC by typing “MMC” at the run. You can configure a lot of programs and objects through MMC

Page 7: OS Lab Manual

8. Intellimirror: Intellimirror provides enhanced access to the information and software. Intellimirror technology is useful for the mobile computer users. Intellimirror requires Windows 2000 server to run and the offline feature enables users to work on their important files when the network connections are unavailable.

9. Group Policy: Group policy feature of the Windows 2000 Professional operating system enables the System/Network Administrators to define rules about security, desktop settings, application settings and user rights. Group policy works with the active directory and it requires Windows 2000 Server.

10. Hibernation: Hibernation is a very useful utility in Windows 2000 Professional and when you re-activate/turn on your computer hibernation restores your programs without losing your data.

11. Synchronization: Synchronization makes your files and folders updated by comparing the files and folders on the network server.

12. Offline Viewing: Offline Viewing feature in Windows 2000 Professional makes entire web pages including graphics for offline view when internet is not available.

13. Plug and Play: More than 65,000 devices support this functionality and it is used for installing the new hardware without the minimum configurations and work at the user end.

14. Auto Correct: Auto Correct feature automatically corrects the URL conventions such as http, com, and .org errors.

15. Automated Proxy: Automated proxy feature in Windows 2000 Professional automatically locate the proxy server on the network and connect to the internet through that proxy server.

16. Internet Connection Sharing: ICS or Internet Connection Sharing connects your home of office computer to the internet through the Dial-Up or broadband internet connection such as DSL, Cable Net etc.

17. Net Meeting: With Net Meeting Conferencing software you can have real time online chat, teleconferencing with the people throughout the world.

PROGRAM - 3

TO STUDY THE GENERAL PURPOSE COMMANDS IN LINUX.

1. Date

Page 8: OS Lab Manual

Print the current Date and Time. You may specify a display format. Format can consist of literal text strings (blanks must be quoted) as well as field descriptors, whose values will appear as described in the following entries. A privileged user can change the system's date and time.Display current date in a nonstandard format. For example:$ date +"%A %j %n %k %p" Tuesday 248 15 PM The default is %a %b %e %T %Z %Y (e.g., Tue Sep 5 14:59:37 EDT 2005).

+%a Abbreviated weekday name (e.g. sun). +%b Abbreviated month name (e.g. jan). +%e Day of month (e.g. 01) +%T Time in %H:%M:%S format. +%Y Four-digit year (e.g., 2006). +%Z Alphabetic time zone abbreviation (e.g., EDT). +%m Month of year (01-12). +%h Abbreviated month name (e.g. jan). +%y Last two digits of year (00-99). +%D Date in %m/%d/%y format. +%H Hour in 24-hour format (00-23). +%M Minutes (00-59). +%S Seconds (00-59).

2. cal

cal [options] [[month] year] Print a 12-month calendar (beginning with January) for the given year, or a one-month calendar of the given month and year. Month ranges from 1 to 12. Year ranges from 1 to 9999. With no arguments print a calendar for the current month.

-m Display Monday as the first day of the week. -y Display entire year calendar. -1 Display current month calendar.

-3 Display previous, current and next month calendar.

3. echo

echo [options] [string] Send (echo) the input string to standard output. This is the /bin/echo command. Echo also exists as a command built into bash.

4. who

who [options] [file] Show who is logged into the system. With no options, list the names of users currently logged in, their terminal, the time they have been logged in, and the name of the host from which they have logged in. An optional system file (default is /etc/utmp) can be supplied to give additional information.

5. Ps

Page 9: OS Lab Manual

The ps (i.e., process status) command is used to provide information about the currently running processes, including their process identification numbers (PIDs).

The basic syntax of ps is ps [options]

When ps is used without any options, it sends to standard output, which is the display monitor by default, four items of information for at least two processes currently on the system: the shell and ps. A shell is a program that provides the traditional, text-only user interface in Unix-like operating systems for issuing commands and interacting with the system, and it is bash by default on Linux. ps itself is a process and it dies (i.e., is terminated) as soon as its output is displayed. The four items are labeled PID, TTY, TIME and CMD. TIME is the amount of CPU (central processing unit) time in minutes and seconds that the process has been running. CMD is the name of the command that launched the process. TTY (which now stands for terminal type but originally stood for teletype) is the name of the console or terminal (i.e., combination of monitor and keyboard) that the user logged into, which can also be found by using the tty command. This information is generally only useful on a multi-user network. .

6. pwd (Print working directory)

Use the pwd command to print the working directory (the current directory you are in).Example

>pwd/home>cd/home/rich/www>pwd/home/rich/www>

Line 1 of this example shows the command pwd has been enteredLine 2 displays, or 'prints' the output of the pwd command (ie: the directory you are in - /home in this case)Line 3 uses the cd command (change directory) to move to the /home/rich/www directoryLine 4 enters the pwd command againLine 5 shows we are now in the /home/rich/www directoryLine 6 is the prompt again.

7. tty

tty [options] Print the filename of the terminal connected to standard input.

Example$tty/dev/pts/10The terminal file name is 10 (a file named 10) resident in the pts directory. This directory in turn is under the /dev directory.

8. bc Calculator.

Page 10: OS Lab Manual

When bc invoked without arguments, the cursor keeps on blinking and nothing seems to happen. bc belongs to a family of commands (called filters) that expect input from the keyboard when used without an argument. key in the following arithmetic expression and then use [ctrl-d] to quit bc.

Examples:$ bc12 + 517bc shows the output of the computation in the next line.

We can make multiple calculations in the same line, using the ; as delimeter. The output of each computation is, however, shown in a separate line:12 * 12 ; 2^32 ^ indicate “to the power of”1444294967296 Maximum memory possible on a 32-bit machine.

bc performs only integer computation and truncates the decimal portion it sees.9 / 51

To enable floating-point computation, set scale to the number of digits of precision before you key in the expression:scale=217 / 72.42 Not rounded off, result is actually 2.42857……

bc is quite useful in converting numbers from one base to another (not exceeding 16). To convert binary numbers to decimal set ibase (input base) to 2 before you provide the number.ibase=211001010202 Outout in decimal – base 10

The reverse is also possible with obase:obase=2141110 Binary in 14

9. man man [options] [section] [title] Display information from the online reference manuals. man locates and prints the named title from the designated reference section.Traditionally, manpages are divided into nine sections, where section 1 consists of user commands, section 2 contains system calls, and so forth. By default, all sections are consulted, so the section option serves to bypass the most common entry and find an entry of the same name in a different section (e.g., man 2 nice).

Page 11: OS Lab Manual

PROGRAM 4

TO STUDY THE FILE MANIPULATION COMMANDS IN LINUX.

The file is a container for storing information.

CATEGORIES:-

Ordinary file Directory file

Page 12: OS Lab Manual

Device file

ORDINARY FILE:-Also known as regular file.

o Text file:- contains only printable characters.o Binary file:- Contains both printable and unprintable characters.

DIRECTORY FILE:-It contains no data but keeps some details of the file and

subdirectories that contains it.

DEVICE FILE:- All devices and peripherals are represented by files. To read or write

a device, you have to perform these operations on its associated file.

COMMANDS

1. CAT:displaying and reating files.

cat [options] [files] Read (concatenate) one or more files and print them on standard output. You can use the > operator to combine several files into a new file, or >> to append files to an existing file. When appending to an existing file, use Ctrl-D, the end-of-file symbol, to end the session.

Examples

cat file1.txt :- Display the content of file1.txt.

cat file1.txt file2.txt > file3.txt :- Reads file1.txt and file2.txt and combines those files to make file3.txt and display the contents of file3.txt .

cat file1.txt>>file2.txt :- Contents of file1.txt are appended at the end of file2.txt

e.g:- $cat>vidushiHelloWelcome to NGFCET[ctrl-z]$_

2. cpcp command copies a file. If I want to copy a file named oldfile in a current directory to a file named newfile in a current directory. cp oldfile newfileIf I want to copy oldfile to other directory for example /tmp thencp oldfile /tmp/newfile.

Useful options available with cp are -p and -r . -p options preserves the modification time and permissions, -r recursively copy a directory and its files, duplicating the tree structure.

3. rm :- Deleting files.

rm filename

Page 13: OS Lab Manual

To delete all files:rm*

Options:-

-i:- For making commands more interactive.

4. MV:- Renaming files

It renames a file. It moves a group of files to a different directory.

$ mv <old file name> <New file name>

5. WC:- Counting lines, words and characters.

$ wc filename

Output in the format:- lines words characters

OPTIONS:-

i. wc –l filenameii. wc –w filename

iii. wc –c filenameiv. wc –l-c filename

6. CMP:- Comparing two files.

$ cmp file1 file2

To files are compared byte by byte and the location of first mismatch is echoed to the screen.

7. LS:- Listing of all the files in the current directory.

OPTIONS:-

i) $ls-l: listing file attributes like permissions, size,ownership.

8. chmod:- Changing file permissions

Relative permissions:-

File permissions:-

r- readw- write

Page 14: OS Lab Manual

x- execute

$ chmod u_x filename$ chmod ugo+r filenameChmod a-x,go+r filename;ls –l filename

ABSOLUTE PERMISSIONS:-

OCTAL PERMISSIONS SIGNIFICANCE000 0 --- NO PERMISSION001 1 --X EXECUTABLE

ONLY010 2 -W- WRITEABLE011 3 -WX WRITABLE AND

EXECUTABLE100 4 R-- READABLE101 5 R-X READABLE AND

EXECUTABLE110 6 RW- READABLE AND

WRITEABLE110 7 RWX READABLE,

WRITABLE AND EXECUTABLE

$ chmod 666 filename;ls –l filename

10. head: - used to display the no of lines of all files. By default it displays 10 lines from starting.

head -3 filename // It displays 3 lines.

11. tail :- By default it displays 10 lines from bottom.

$ tail -3 filename // displays 3 lines from bottom

12. nl :- for numbering

$ nl filename

Output:-1. hello 2. gud afternoon3. jmdsfk

13. grep:- Pattern searching

$ grep pattern filename

Page 15: OS Lab Manual

Only those lines which have pattern will be displayed.

Option:- $grep –i pattern filename (it ignores uppercase and lower case letters)

14. pipeline command :- output of one becomes input of second command.

$ls|wc –l/ filename

15. gzip :- To compress the file.

Syntax:- $gzip filename

e.g. $wc –l filename3875302 filename$gzip filename$ wc –c filename788096 filename.gz.

Option:- uncompressing a gzipped file-(-d)To restore the original file, we have two options.

i. gzip –dii. gunzipiii. eg. Gunzip filename.gz

PROGRAM 5

TO STUDY THE DIRECTORY COMMANDS IN LINUX.

1. mkdir

mkdir command is used to create directories.

Page 16: OS Lab Manual

2.rmdir

The rmdir(remove directory ) command removes directories. You simply have to do this to remove the directory pis

rmdir pis directory must be removed

3. passwdpasswd: Change password. It brings up dialogue that allows you to change your password.

4. script(recording your session)If you are doing some important work and wish to keep a log of all your activities,you should invoke this command immediately after you log in:

$ script script started, file is typescript$ -

5. uname

The uname command displays certain features of the operating system running on your machine. By default, it simply displays the name of the operating system. Display host name and info of current systemoptions: -r print OS release level -a prints basic info | -s prints the name of the OS (default)

PROGRAM-6 

WRITE A SCRIPT TO SEE CURRENT DATE, TIME, USERNAM E AND CURRENT DIRECTORY.

Script: -

Page 17: OS Lab Manual

printf "current date and time is"dateecho "  "printf "the user logged in is"lognameecho "  "printf "and current directory is"pwd 

Output:-

$ sh prog7current date and time isThu Apr  1 09:23:12 EDT 2010 the user logged in isdeepika and current directory is/home/deepika 

PROGRAM-7

WRITE A SCRIPT TO FIND A GIVEN PATTERN IN GIVEN FILE WHERE PATTERN AND FILENAME ARE GIVEN AS COMMAND LINE ARGUMENT.  

Page 18: OS Lab Manual

Script:-

pattern=$1filename=$2echo "pattern=" $patternecho "filename=" $filenamegrep "$pattern" $filename  

Output:-

$ sh prog8 current prog7pattern= currentfilename= prog7printf "current date and time is"printf "and current directory is"  

PROGRAM-8

WRITE A SCRIPT TO SEARCH STRING AND FILE LINK FROM TERMINAL. 

Page 19: OS Lab Manual

Script:-

echo "enter the pattern to be searched"read pnameecho "enter the file to be used"read fnameecho "searching for $pname from file $fname"grep "$pname" $fname   

Output:-

$ sh prog9enter the pattern to be searcheddirectoryenter the file to be usedprog7searching for directory from file prog7printf "and current directory is"  

PROGRAM-9

WRITE A SCRIPT TO ACCEPT TWO FILENAMES AND CHECK IF BOTH EXISTS AND THEN APPEND ONE FILE TO ANOTHER.    

Page 20: OS Lab Manual

Script:-

echo "the number of arguments given is $#"if test -f $1thenif test -f $2thencat $1>>$2echo "file $1 append to file $2"elseecho "file with name $2 does not exist"fielseecho "file with name $1 does not exist"fi  

Output:-

$ sh prog10 prog7 abcthe number of arguments given is 2file with name abc does not exist 

PROGRAM-10

WRITE A SCRIPT TO FIND THE LARGEST NUMBER FROM GIVEN THREE NUMBERS.  

Page 21: OS Lab Manual

Script:-

if test $1 -ge $2 -a $1 -ge $3thenecho "the greatest number is $1"elif test $2 -ge $1 -a $2 -ge $3thenecho "the greatest number is $2"elseecho "the greatest number is $3"fi 

Output:-

$ sh prog11 56 34 74the greatest number is 74

PROGRAM - 11

WRITE A SCRIPT TO PRINT PYRAMID OF NUMBERS.

Page 22: OS Lab Manual

Script:-

for(( i=1 ; i<=5 ; i++))do

for(( j=1 ; j<=i; j++))do

printf $idoneecho “ ”

done

Output:-

12 23 3 34 4 4 45 5 5 5 5

PROGRAM-12 WRITE A SCRIPT TO FIND OUT THE LENGTH OF A STRING AND EXTRACTING A SUBSTRING FROM IT.

Page 23: OS Lab Manual

Script:-

str=2003str1=abcdefecho "enter your name"read nameecho `expr "$name" : '.*'`echo `expr "$str" : '..\(..\)'`echo `expr "$str1" : '[^d]*d'`  

Output:- 

$ sh prog13enter your namedeepika7034 

  

 

PROGRAM-13

Page 24: OS Lab Manual

WRITE A SCRIPT USING CASE STATEMENT TO PERFORM BASIC ARITHMATIC OPERATIONS.

Script:-  

case $2 in+) echo `expr $1 + $3`;;-) echo `expr $1 - $3`;;\*) echo `expr $1 \* $3`;;/) echo `expr $1 / $3`;;esac  

 Output:-

$ sh prog15 12 / 43

PROGRAM-14

Page 25: OS Lab Manual

WRITE A SCRIPT TO PRINT REVERSE OF A NUMBER.

Script:- 

s=0n=$1while test $n -ge 1dox=`expr $n % 10`n=`expr $n / 10`s=`expr $s \* 10 + $x`doneecho "the reverse of digits is " $s 

Output: -

sh prog16 34578the reverse of digits is  87543   

PROGRAM-15 

Page 26: OS Lab Manual

WRITE A SCRIPT TO PRINT SUM OF DIGITS.

Script:-

s=0n=$1while test $n -ge 1do x=`expr $n % 10`n=`expr $n / 10`s=`expr $s + $x`doneecho "the sum of digits is" $s  

Output:-

$ sh prog17 5777the sum of digits is 26  

PROGRAM-16

Page 27: OS Lab Manual

WRITE A SCRIPT TO FIND IF A GIVEN NUMBER IS ARMSTRONG OR NOT.

Script:- 

s=0n=$1t=$1while test $n -ge 1dox=`expr $n % 10`n=`expr $n / 10`s=`expr $s + $x \* $x \* $x`doneif test $t -eq $sthenecho "the no. is armstrong"elseecho "the no. is not armstrong"fi  

Output:-

$ sh prog18 153the no. is armstrong 

PROGRAM-17

Page 28: OS Lab Manual

WRITE A SCRIPT TO CHECK WHEATHER A NUMBER IS PALINDROME OR NOT. 

Script:- 

s=0n=$1t=$1while test $n -ge 1dox=`expr $n % 10`n=`expr $n / 10`s=`expr $s \* 10 + $x`doneif test $s -eq $tthenecho "the no. is palindrome"elseecho "not palindrome"fi 

Output:-

$ sh prog19 12321the no. is palindrome 

Page 29: OS Lab Manual

PROGRAM-18

 WRITE A SCRIPT TO PRINT FIBONACCI SERIES.

Script:-

 

a=0b=1echo $aecho $bwhile test $1 -ge $bdoa=`expr $a + $b`b=`expr $a + $b`echo $aecho $bdone 

Output:-

$ sh prog20 7011235813

AWK – AN ADVANCE FILTER

Page 30: OS Lab Manual

The AWK command made a late entry into the UNIX system 1977 to augment the tool kit with suitable report formattimg capabilities. Named after its authors, Aho, Weinberger and Kernighan, awk, until the advent of perl, was the most powerful utility for text manipulation.Awk doesn’t belong to the do-one-nothing-well family of unix commands. In fact, it can do several things- and some of them quite well.

SIMPLE AWK FILTERING:-

Awk options ‘selection criteria {action}’ file(s)

The selection criteria filter input and selects lines for the action component to act upon.e.g.:-

$ awk ‘/director/{print}’emp.lst

SPLITTING A LINE INTO FIELDS:-Awk uses the special

parameter, $0, to indicate the entire line. It also identifies fields bi $1, $2, $3.e.g:-

$ awk –F”|” ‘/sales/ {print $2, $3, $4, $6}’ emp.lstHead –n 2 emp.lst

If you want to select lines 3 to 6

$awk –F”|” ‘ NR==3, NR==6{print NR,$2,$3,$6}’emp.lst

Printf: FORMATTING OUTPUT:-

$ awk –F”|” ‘/[aA]gg?[ar]+wal/{>Printf “%3d %-20s %-12s %d\n”,NR,$2,$3,$6}’emp.lst

Page 31: OS Lab Manual

VARIABLES AND EXPRESSIONS:-

X=”5”Print x

e.g 2:-x=”sun”;y=”com”print x,yprint x “.” Y

THE COMPARISION OPERATOR:-

$awk –F”|” ‘$3==”director”||$3==”chairman”{>printf “%-20s % -12s %d\n”,$2,$3,$6}’emp.lst

VARIABLES:-

$awk –F”|” ‘$3==”director” && $6>6700{>kount=kount+1>printf “%3d %-20s %-12s %d\n”,kount,$2,$3,$6}’emp.lst

LOOPING WITH WHILE:-

K=0While(k<(65-length($0))/2){Printf “%s”,””K++}Print $0