Sei sulla pagina 1di 85

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

INTRODUCTION
Linux is a freely distributed operating system that behaves like the Unix operating system. Linux was designed specifically for the PC platform and takes advantage of its design to give users comparable performance to high-end UNIX workstations. Many big-name companies have joined the Linux bandwagon such as IBM and Compaq, offering systems pre-installed with Linux. Also, many companies have started Linux packages, such as Red Hat, Corel, and Samba. However, they can only charge for services and documentation packaged with the Linux software. More and more businesses are using Linux as an efficient and more economical way to run their networks. Linux is a complete multitasking, multi-user operating system that behaves like UNIX in terms of kernel behavior and peripheral support. Linux has all the features of UNIX and boasts of its open source code and mainly free utilities. The Linux kernel was originally developed for the Intel 80386, which was developed with multitasking as one of its features. The kernel is the lowest-level core factor of the operating system. The kernel is the code that controls the interface between user programs and hardware devices, the scheduling of processes to achieve multitasking, and many other aspects of the system. The Linux kernel is a monolithic kernel; all the device drivers are part of the kernel proper. Despite the fact that most of Intel's CPUs are used with single-tasking MS-DOS, Linux makes good use of the advanced multitasking features built into the CPU's instruction set. Linux supports demand paging, which means that only the sections of a program that are necessary are read into RAM. Linux also offers support for copy-on-write, a process that if more than one copy of a particular application is loaded, all tasks can share the same memory. When large memory requirements are needed and only small amounts of physical RAM are available, Linux has another feature called swap space. Swap space allows pages of memory to be written to a reserved area of a disk and treated as an extension of physical memory. By moving pages between the swap space and RAM, Linux can, in effect, act as if it had much more physical RAM than it does, with the cost of some speed due to the hard drive's slower access. Linux also supports diverse file systems, as well as those compatible with DOS and OS/2. Linux's file system, ext2fs, is intended for best possible use of the disk. The History of Linux Linux is a freely distributable version of UNIX. UNIX is one of the most popular operating systems for networking worldwide because of its large support base and distribution. Linus Torvalds, who was then a student at the University of Helsinki in Finland, developed Linux in 1991. It was released for free on the Internet and generated the largest software-development phenomena of all time. Because of GNU software (GNU being an acronym for Gnu's Not UNIX) created LINUX LAB MANUAL 1

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

by the Free Software Foundation, Linux has many utilities to offer. The Free Software Foundation offers royalty-free software to programmers and developers. From the very beginning, Linux has been entwined with GNU software. From 1991, Linux quickly developed on hackers' web pages as the alternative to Windows and the more expensive UNIX systems. When Red Hat released its commercial version of Linux packaged with tech support and documentation, the floodgates broke and the majority of the public became aware of Linux and its capabilities. Now more and more new users are willing to try Linux on their personal PCs and business users are willing to use Linux to run their networks. Linux has become the latest phenomenon to hit the PC software market. Linux is a unique operating system in that it is an active participant in the Open Source Software movement. Linux is legally covered by the GNU General Public License, also known as GPL. Open Source software is free but is not in the public domain. It is not shareware either. GPL allows people to take free software and distribute their own versions of the software. However, the vendors who sell free software cannot restrict the rights of users who purchase the software. In other words, users who buy GPL software can make copies of it and distribute it free of charge or for a fee. Also, distributors of GPL software must make it clear that the software is covered by the GPL and must provide the complete source code for the software at no cost. Linux embodies the Open Source model. Open source applies to software for which the source code is freely available for anyone to download, alter, and redistribute. Linux is the perfect operating system for hackers because they can freely download newer versions of the Linux kernel or other Linux utilities of the Internet and instantly change its source code to fix any software bugs found. That way, bugs can be fixed in a matter of hours as opposed to days and weeks. Beta testers and code debuggers are unorganized and spread throughout the world, but surprisingly, they have managed to quickly debug Linux software efficiently and cooperate online through the use of the Internet. What is a distribution? Think of it as ice cream flavors- each is unique but are generally similar. Because Linux is open-sourced, there are numerous distributions that programmers have worked on, but the most popular are talked about below. RedHat Linux- Lately, RedHat has been making the headlines with it's Linux distribution. It is one of the most popular distributions out there right now, and supports the Intel, Alpha, and SPARC platforms. Many users prefer RedHat Linux because of its ease of use, installation, and live tech support. RedHat Linux primarily comes bundled with the X Windows System, GNOME and KDE desktop environments, as well as the StarOffice suite. Linux Mandrake- Yet another rather popular distribution is Linux Mandrake. Similar to RedHat, it also bundles the X Windows System,

LINUX LAB MANUAL

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

GNOME, KDE, and StarOffice. What really distances Mandrake from RedHat Linux is its improved ease of use plus a few added extra tools and utilities. Corel Linux- Although less popular than something like RedHat, Corel Linux continues to shine with its usability and ease of installation through its Install Express. It comes with only the KDE environment, but also includes WordPerfect for Linux instead of Sun's StarOffice. Debian/GNU- Debian/GNU is intended for the more advanced Linux users out there. Although it is more difficult to use than other distributions, Debian/GNU is frequently chosen for web server purposes. Its stability and web adminstration tools are the reason many webmasters rely on Debian/GNU for their server environment. Slackware- As one of the first distributions of Linux created, Slackware continues to be fairly popular. It also includes the usual X Window System, GNOME, and KDE. Slackware boasts excellent stability, at the expense of less updated code and more intermediate to advanced user appeal. SuSE Linux- If you're looking full feature bundles with your Linux distribution, try SuSE Linux. Originally created by German programmers, this distribution has become quite popular in Europe and is gaining much recognition in the United States. Of course it includes the standard X Windows System, KDE and GNOME environments, but it distances itself from the other offerings by including a huge amount of bundled software. This distribution is also recommended for newer users. Caldera OpenLinux- Primarily designed for the business and power user, Caldera Linux focuses on internet applications. It includes a full collection of internet connectivity and access tools, and helps anyone take full of advantage of the internet through Linux. Keep in mind that all of these distributions are very similar to each other, and their software bundles tend to be too. One major consideration that you should make when choosing a distribution is what you plan on using it for, and if you need particular software applications with it. Your best bet is to go and get an actual CD with the distribution, since it makes it much easier to install and run. You can always try to download it for free, but you'll probably end up finding it to be rather time consuming and difficult. For example, the best distributions for the new user would be RedHat, Mandrake, Corel, and SuSE. A power or internet-oriented user would probably choose something like Caldera, Slackware, or Debian/GNU. Note that there are also hundreds of distributions not covered by this section, but are probably just as good as some of the ones listed above.

LINUX LAB MANUAL

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

Linux Versus the World


Why Linux? There are many reasons to use Linux. Linux is an affordable alternative to the more expensive Unix operating system. It allows users to develop and test Unix software without having to spend money to buy the operating system. Linux is freely available on the Internet. For college students, Linux provides them opportunity to run and learn about a Unix based operating system on their own personal computers, making them more aware of how to run Unix on their university computer networks. Linux is not just for personal computer users. It is able to handle bigger tasks of running large networks. Many businesses are turning to Linux to run their workstations. An increasing number of people are becoming aware of the powerful features Linux has to offer and many are switching over to Linux. Linux Versus Windows 95 and Windows 98 Linux and Windows 95/98 are two totally different operating systems. Comparing them would be like comparing apples and oranges. Windows 95/98 is run on personal PCs and is not used to manage no more than a small home network. The popularity of Windows 95/98 is based on its low cost and availability to personal PC users. Instead of spending several thousands of dollars on a commercial operating system, Windows offers a fully functional operating system that can be used to perform many tasks such as connecting to the Internet, word processing, gaming, and many others. As an alternative, Linux can be run on a personal PC, albeit without unleashing the full networking power of Linux. Yet, for users willing to experiment with a new operating system and test out the features of Unix, Linux is for them. Although commercial software for Linux is growing, it still remains pitifully small compared to the number of programs out on the market support Windows 95/98. Word processing through Microsoft Word and its Office Suite is extremely easy. The Star Office suite by Sun Microsystems is an open source office suite for Linux that is gaining in popularity. It allows users to save and load .doc files, making it easier to interact between Microsoft Word and Windows. Gaming is growing on Linux but Windows 95/98 still has the upper hand on commercial games. Therefore, many Linux users use Windows 95/98 concurrently and there are many tools available to Linux that allows Linux users to access Windows files. Also the Wine Windows emulator allows users to run many popular Windows applications.

LINUX LAB MANUAL

LINUX OPERATING SYSTEM MANUAL Linux Versus Windows NT

ENGR. JULIUS S. CANSINO

Microsoft's Windows NT is becoming very popular for server computing. Windows NT is similar to Linux in that it is a full multitasking operating system, supporting multiprocessor machines, several CPU architectures, virtual memory, networking, security, and several other features. The main difference between Windows NT and Linux is that Linux is based on the Unix platform, Unix being the more widely used operating system to run networks in large corporations. Since Linux is a version of Unix, it benefits from any contribution made to both the Linux and the Unix communities. Many vendors distribute Unix and no single corporation controls the design for standardization. Linux suffers from the same problem. Windows NT is a proprietary system. A single corporation, Microsoft, controls its interface and design and only Microsoft may implement any changes to its code. This type of organization is beneficial in that it sets a standard for the operating system. However, it does not implement any of the Open Source ideals that Linux embraces. Windows NT is not likely to be offered for free anytime in the future. Although both Linux and Windows NT exhibit different strengths and weaknesses, Linux prevails over NT in the area of networking performance. Linux is also much smaller that NT and uses less system resources. In addition, Linux crashes less frequently than NT. Linux has been known to run continuously on systems for several months, while NT has a notorious reputation for crashing often. For a operating system quite new and lacking the "brand name" of Windows, in the past year, Linux has become a rather serious competition to the Windows operating system. Microsoft has begun to give Linux a second glance, and maybe even a hard stare. Linux Versus Unix In terms of features, Unix and Linux are quite similar. However, the major difference between Unix and Linux is that Unix was designed specifically for networking. Linux runs perfectly fine as a personal Unix system and on large servers. Linux supports a much wider range of hardware than Unix and because of the Open Source model, any driver for certain hardware can be written for Linux as long as someone has the time to do so. Many universities and companies are beginning to use Linux instead of Unix because it can provide the functionality of a workstation on PC hardware at a fraction of the cost. There are other free Unix versions available such as FreeBSD. FreeBSD and Linux are similar but based on different goals and therefore designed differently. The goal of Linux was to develop a free Unix system that could be run on both a personal level and on large network servers. FreeBSD sought only to modify the existing BSD Unix code. Another inexpensive implementation of Unix is Minix, an academic Unix clone upon which earlier versions of Linux was based on. However, despite all the other Unix systems being developed and marketed, it can be clearly seen that more and more users are turning towards Linux to run their systems.

LINUX LAB MANUAL

LINUX OPERATING SYSTEM MANUAL Conclusion

ENGR. JULIUS S. CANSINO

The choice is for you to make. You've read our guide and only you can make the decision. If you're feeling adventurous or if you're just bored of Windows, go out and grab a copy of Linux and try it for yourself. Once you get it working on your machine, the possibilities are endless.

LINUX LAB MANUAL

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

Experiment No. 1

FILE OPERATION COMMANDS


OBJECTIVES 1. to create and edit a file 2. to perform tasks involving files, including copying, moving, and printing by using the file operation commands DISCUSSION A file is a collection of information that you can refer to by a filename. It is frequently stored on a disk. Text files typically contain memos, reports, messages, program source code, lists or manuscripts. An editor is a utility program that allows you to create a new text file or change a text file that already exists. Many editors are in use on Linux systems. Linux utility programs allow you to work with Linux and manipulate the files that you create. Some of the utilities that you can use to create and manipulate files: joe, cat, diff, cmp, rm, mv, cp and pr. The following utilities perform various tasks involving files, including copying, moving, and printing them.

joe
Syntax: $ joe [filename] Joe (Joes Own Editor) is an easy-to-use, interactive, visually-oriented text editor. If joe is not available, you may need to install it from your Linux CD. You can start with vi or emacs. The joe editor is not a text formatting program. The following command to start joe and to edit the file named sample. $ joe sample

cat
Syntax: cat [options] [file-list]

LINUX LAB MANUAL

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

The cat utility joins or displays files. The cat utility joins files end to end. It takes its input from files you specify on the command line or from standard input. You can use cat to display the contents of one or more text files on the terminal. The name cat is derived from one of the function of this utility, catenate, which means to join together sequentially, or end to end. The following command line displays on the terminal the contents of the text file named memo: $ cat memo I love you. I am happy with you. The next example catenates three files and redirects the output to a file named all. $ cat docu letter memo > all You can use cat to create short text files without using an editor. Enter the command line shown below, type the text that you want in the file, and then press CONTROL + D on a line by itself. The cat utility takes its input from standard input(the terminal), and the shell redirects standard output to the file you specify. The CONTROL + D signals the End of File and causes cat to return control to the shell. $ cat > new_file . . (text) . . CONTROL + D

diff
The diff utility displays the difference between two files. It displays the differences between two files on a line-by-line basis. It displays the differences as instructions that you can use to edit one of the files to make it the same as the other.

LINUX LAB MANUAL

LINUX OPERATING SYSTEM MANUAL Syntax: diff [options] file1 file 2 diff [options] file1 directory diff [options] directory file2 diff [options] directory1 directory2

ENGR. JULIUS S. CANSINO

The file1 and file2 are pathnames of the files that diff works on. When the directory2 argument is used in place of file2, diff looks for a file in directory2 with the same name as file1. Similarly, when the directory argument is used in place of file1, diff looks for a file in directory1 with the same as file2. When you specify two directory arguments, diff compares all files in directory1 with files in directory 2 that have the same names. When you use diff without any options, it produces a series of lines containing Add (a), Delete (d), and Change (c) instructions. Each of these lines is followed by the lines from the file that you need to add, delete, or change. A less than symbol (<) precedes lines from file1. A greater than symbol (>) precedes lines from file2. The diff output is in the format shown below. A pair of line numbers separated by a comma represents a range of lines; diff uses a single line number to represent a single line. Instruction Line1 a line2,line3 >lines from file2 Line1, line2 d line 3 <lines from file1 Line1, line2 c line3, line4 <lines from line1 -->lines from line 2 Meaning Appends lines from file2 after line1 in file1 Delete line1 through line2 from file1 Changes line1 through line2 in file1 to lines from file2

The diff utility assumes that you are going to convert file1 to file2. The line numbers to the left of each of the a, c, or d instructions always pertain to file1; numbers to the right of the instructions apply to file2. To convert file1 to file2, ignore the line numbers to the right of the instructions.

LINUX LAB MANUAL

LINUX OPERATING SYSTEM MANUAL Examples:

ENGR. JULIUS S. CANSINO

The first example shows how diff displays the differences between two short, similar files: $ cat f1 aaaaa bbbbb ccccc $ cat f2 aaaaa ccccc $ diff f1 f2 2d1 <bbbbb The first line 2d1 indicates that you need to delete the second line from file1 (f1) to make it the same as file2 (f2). The next example uses the same file f1 and a new file p, to show diff using an a(append) instruction. $ cat p aaaaa bbbbb rrrrr ccccc $ diff f1 p 2a3 >rrrrr The line 2a3 indicates that you must append a line to file f1, after line2, to make it the same as file p.

LINUX LAB MANUAL

10

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

The next example uses f1 again, this time with file r, to show how diff indicates a line that needs to be changed: $ cat r aaaaa -q ccccc $ diff f1 r 2c2 < bbbbb -->-q The difference between the two files is in line2: File f1 contains bbbbb, and file r contains q. Above, diff displays 2c2 to indicate that you need to change line2. After indicating that a change is needed, diff shows that you must change line2 in file f1(bbbbb) to line2 in file r(-q) to make the files the same. The three hypens indicate the end of the text file f1 that needs to be changed and the start of the text in file r that is to replace it. $ cat t aaaaa lllll hhhhh nnnnn $ diff f1 t 2, 3c2, 4 < bbbbb < ccccc --> lllll > hhhhh > nnnnn Here diff indicates that you need to change lines2 through (2,3) in file f1 from bbbbb and ccccc to lllll, hhhhh, nnnnn.

LINUX LAB MANUAL

11

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

cmp
Syntax: cmp [options] file1 [file2] The cmp utility checks two files to see if they differ. It does a byte-by-byte comparison of file1 and file2. If the files differ, cmp outputs the location at which the first difference occurs. The cmp utility returns an exit status of 0 if the files are the same and exit status of 1 if they different. An exit status of 2 means that an error has occurred. The cmp utility only sets the exit status and does not display any output if the files are identical. When cmp displays the bytes that are different in the two files, the byte from file1 is shown first, followed by the byte from file2. The following examples use the files a and b shown below. These files have two difference is that the word lazy in file a is replaced by lasy in file b. The second difference is more subtle; there is a TAB character just before the NEWLINE character in file b. $ cat a The quick brown fox jumped over the lazy dogs back. $ cat b The quick brown fox jumped over the lasy dogs back.TAB The first example uses cmp without any options to compare the two files. The cmp utility reports that the files are different and identifies the offset from the start of the files where the first difference is found. $ cmp a b a b differ: char 39, line 1

LINUX LAB MANUAL

12

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

You can see the values of the bytes at that location by adding the print chars option. $ cmp --print--chars a b a b differ: char 39, line 1 is 172 z 163 s

rm
Syntax: rm [options] file-list The rm utility removes links to one or more files. It can be used to remove both hard and symbolic links. When you remove the last hard link, you can no longer access the file, and the system releases the space the file occupied on the disk for use by another file. To delete a file, you must have execute and write access permissions to the parent directory of the file, but you do not need read and write access permission to the file itself. If you are running rm from a terminal and you do not have write access permission to the file, rm displays your access permission and waits for you to respond. If you enter y or yes, rm deletes the file, otherwise it does not. When you want to remove a file that begins with a hypen, you must prevent rm from interpreting the filename as an option. One way to do this is to give the special option before the name of the file. This special option tells rm that no more options to follow arguments that come after it are the filenames, even if they look like options. The following command lines delete files, both in the working directory and in another directory: $ rm memo $ rm letter memo1 memo2 $ rm /home/jenny/temp

LINUX LAB MANUAL

13

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

The next example asks the user before removing each file in the working directory and its subdirectories. This command is useful for removing filenames that contain special characters, especially SPACEs, TABs and NEWLINEs. $ rm ir

mv
Syntax: mv [options] existing-file new-filename mv [options] existing-file-list directory mv [options] existing-directory new-directory The mv utility moves or renames one or more files. It has three formats. The first renames a single file with a new filename you supply. The second renames one or more files so that they appear in a specified directory. The third renames a directory. The mv utility physically moves the file if it is not possible to rename it. You cannot move a directory from one file system to another. The first command line renames letter, a file in the working directory as letter.1201: $ mv letter letter.1201 The next command line renames the file so that it appears, with the same simple filename in the /usr/archives directory: $ mv letter.1201 /usr/archives The following command line renames all the files in the working directory whose names begin with memo so they appear in the /usr/backup directory: $ mv memo /usr/backup

LINUX LAB MANUAL

14

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

cp
Syntax: cp [options] source-file destination-file cp [options] source-file-list destination-directory The cp utility copies one or more ordinary files, including text and executable program files. It has two modes of operation. The first copies one file to another, and the second copies one or more files to a directory. If the destination-file exists before you execute cp, cp overwrites the file, destroying the contents but leaving the access privileges, owner, and group associated with the file as they were. If the destination-file does not exist, cp uses the access privileges of the source-file. The user becomes the owner of the destination-file, and the users group becomes the group associated with the destination-source-file. With the p option, cp always sets the access privileges, owner and group to match those of the source-file. The first command makes a copy of the file letter in the working directory. The name of the copy is letter.sav: $ cp letter letter.sav The next command copies all the files with filenames ending in .c into the archives directory, a subdirectory of the working directory. Each copied file in retains its simple filename but has new absolute pathname. $ cp *.c archives The next example copies memo from the /home/jenny directory to the working directory: $ cp /home/jenny/memo

LINUX LAB MANUAL

15

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

The final command copies the files named memo and letter into another directory. The copies have the same simple filename as the source files but have different absolute pathnames. The absolute pathnames of the copied files are /home/jenny/memo and /home/jenny/letter. $ cp memo letter /home/jenny

pr
Syntax: pr [options][file-list] The pr utility breaks files into pages, usually in preparation for printing. Each page has a header with the name of the file, date, time and page number. The pr utility takes its input from files you specify on the command line or from standard input. The output from pr goes to standard output and is frequently redirected by a pipe to the lpr utility for printing. The first command line shows pr paginating a file named memo and sending its output through a pipe to lpr for printing: $ pr memo | lpr Next, memo is sent to the printer again, this time with a special heading at the top of each page. The job is run in the background. $ pr h MEMO RE: BOOK memo | lpr& [1] 4904 Below, pr displays the memo file on the terminal, without any header, starting with page 3: $ pr t +3 memo

LINUX LAB MANUAL

16

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

Supplementary Exercises1
Directions: 1. Create a file named oey that contains the text below using joe The joe editor is easier to use than vi or emacs although it is not as powerful. It is perfect for someone getting started with Linux because you can use it to create and edit the files you use to learn Linux. One of joes best features is the immediate availability of help. What joe command(s) would you use to a. save a file __________ b. edit a file __________ c. delete a line __________ d. copy a line __________ e. move a line __________ f. undo an action __________ g. redo an action __________ h. leave the joe editor __________ 2. Create two copies of the file joe using the filename jayr and cha under the /home directory. Command: _____________________________________________________ 3. Rename the file jayr to oeyr using mv command. Command: _____________________________________________________ 4. Request a removal of the file joe. Command: _____________________________________________________

5. Confirm the files that are removed using the ls command. Command: _____________________________________________________

LINUX LAB MANUAL

17

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

Output:

6. Create another file named sam that contains the text below using cat command. Command: _____________________________________________________ Emacs Editor is a very popular text editor in the Linux world. 7. Given another file named julian that contains the text below, what do you think will be the output in performing the command $ diff sam julian? Emacs Editor is a very popular in the Linux world. Output:

8. Using the given in no. 7, what do you think will be the output in performing the command $ cmp sam julian? Output:

LINUX LAB MANUAL

18

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

DIRECTORY COMMANDS
OBJECTIVES 1. to identify pathnames of a given file contained in a directory 2. to perform tasks involving deleting directories, copying and moving directories DISCUSSION LINUX FILESYSTEM A filesystem is a data structure that usually resides on part of the disk. The Hierarchical Filesystem A hierarchical structure frequently takes the shape of a pyramid. The Linux filesystem resembles like a tree. It is composed of a set of connected files. This structure allows users to organize files so they can easily find any particular one. In a standard Linux system, each user starts with one directory, users can make as many subdirectories as they like, dividing subdirectories into additional subdirectories. Directory and Ordinary Files The tree representing the file system grows downward from the root, with paths connecting the root to each of the other files. At the end of each path is either an ordinary file or a directory file. Ordinary files, frequently just called files, are at the ends of paths that cannot support other paths. Directory files, usually referred to as directories, are the points that the other paths can branch off from. Directories directly connected by a path are called parents (closer to the root) and children (farther from the root). A pathname is a series of names that traces a path along branches from one file to another. Filenames Every file has a filename. The maximum length of a filename varies with the type of filesystem. On most file systems, you can create files with names up to 255 characters long, but some filesystems may restrict you to have 14character names. The root directory is always named / and referred to by this single character. No other file can use this name. No two files in the same directory can have the same name. Files in different directories can have the same name.

Experiment No. 2

LINUX LAB MANUAL

19

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

The filenames you choose should mean something like wage, months, first_quarter and grades. Filename Extensions Filename extensions help describe the contents of the file. A filename extension is the part of the filename following an embedded period. Use extensions freely to make filenames easy to understand. Filename compute.c compute.o compute Memo.0410 Memo.gz Memo.tgz Memo.Z Memo.ps Pathnames Every file and directory is identified through a unique pathname. The pathname shows the location of files in the file systems. You can build the pathname of a file by tracing a path from the root directory, through all the intermediate directories, to the file. String all the filenames in the path together, separating them with slashes (/) and preceding them with the name of the root directory (/). / /etc home tmp etc Meaning of Filename Extension A C programming language source file The object code for the program. The same program as an executable file. A text file. A file compressed with gzip. A tar archive of files compressed with gzip. A file compressed with compress. A postscript file.

joey

jayr

his

/home/his

bin

notes

/home/his/notes

report

grade s

/home/his/bin/grade

LINUX LAB MANUAL

20

LINUX OPERATING SYSTEM MANUAL Types of Pathnames

ENGR. JULIUS S. CANSINO

Absolute Pathname An absolute pathname shows the file location starting from the root directory to the file. It is also known as full pathname e.g. /user/unxclass/stud01 which is the stud01 directory, /bin/date which is the executable file date. Relative Pathname A relative pathname traces a path from the working directory to a file. The pathname is relative to the working directory. Any pathname that does not begin with the root directory (/) is a relative pathname. Like absolute pathnames, relative pathnames can describe a path through many directories. Joey could have created the computer directory more easily using a relative pathname. $ pwd /home/joey $ mkdir computer The pwd command shows that Joeys home directory (/home/joey) is still the working directory. Standard Directories and Files The Linux file structure is setup according to a convention named the Linux Filesystem Standard. The figure below shows the locations of some important directories and files, as specified by the Linux Filesystem Standard. A Typical Linux System File Structure / sbin var dev Z mail spool tmp bin sbin joey jayr cha usr etc tmp
home

The root Directory Throughout the decade, developers had tried to define standards for the file system hierarchy and for what each of these directories should be used for. But even with the efforts of all these people there are still variations among all distributions.

LINUX LAB MANUAL

21

LINUX OPERATING SYSTEM MANUAL / /bin /sbin /boot /dev /home /lib /opt /root /tmp /var /etc /initrd /mnt

ENGR. JULIUS S. CANSINO

root directory of the entire system Holds system executables Holds system executables and are essential for starting up the system Holds the files needed during the booting process including the kernel It is a special directory that holds information regarding peripherals /dev/ttys0, /dev/had, etc. Holds all the home directories for all users except root Holds system binary libraries, shared libraries and kernel module Here is where optional applications might go This is the home directory for super user, do not confuse this folder with / Here is where temporary files are stored; it is usually emptied when systems restart. This is where variable system files go, system logging, file locks, printer Spooling, mail spooling and many others. This directory holds almost all configuration files. As administrator you will spending most of your time tweaking settings in this folder. This directory is used at boot time, in the initrd to perform pivot_root This directory is used as a mount point. Here you can temporarily mount medias such as CD-ROM, zip and other file systems. Example: /mnt/windows, /mnt/floppy, mnt/cd-rom This directory is used as a kernel information access hooks, example of usage: [agustin@server2 proc]$cat cpuinfo [agustin@server2 agustin]$cat filesystems

/proc

It is a very large directory, holds application programs; it also has several important additional directories. /usr/bin It contains binaries executables /usr/include This directory contains C headers with various libraries applications. /usr/local It contains the application programs used locally /usr

Linux utility programs allow you to work with Linux and manipulate the directories that you create. Some of the utilities that you can use to create and manipulate directories: ls, cd, mkdir, rmdir and mv. The following utilities perform various tasks involving directories including creating, deleting and displaying.

LINUX LAB MANUAL

22

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

cd
Syntax: cd [directory] When you call cd and specify a directory, that directory becomes the working directory. If you do not specify a directory on the command line, cd makes your home directory the working directory. The following command makes your home directory become the working directory: $ cd The next command makes the /home/alex/literature directory the working directory. The pwd builtin verifies the change. $ cd /home/alex/literature $ pwd /home/alex/literature Next cd makes a directory of the working directory: $ cd memos $ pwd /home/alex/literature/memos Finally, cd uses the .. reference to the parent of the working directory to make the parent the new working directory. $ cd .. $ pwd /home/alex/literature

ls
Syntax: ls [options] [file-list] The ls utility displays information about one or more files. It lists the information alphabetically by filename unless you use an option to change the order.

LINUX LAB MANUAL

23

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

The file-list contains one or more pathnames of file. You can use the pathname of any ordinary, directory or service file. These pathnames can include ambiguous file references. When you specify a directory, ls displays the contents of the directory. The ls utility displays the name of the directory only when it is needed to avoid ambiguity, such as when more than one directory is included in the listing. If you specify an ordinary file, ls displays information about just that file. All of the following examples assume that the user does not change to another working directory. The first command line shows the ls utility with the x option. You see an alphabetical list of the names of the files in the working directory. $ ls x bin execute

c letters

calendar shell

The F option appends a slash (/) to files that are directories, an asterisk to files that are executable, and an at sign @ after symbolic links. $ ls Fx bin/ execute

c/ letters/

calendar shell#

Next, the l(long) option displays a long list. The files are still in alphabetical order. $ ls l total 8 drwxrwxr-x 2 jenny pubs 80 May 20 09:17 drwxrwxr-x 2 jenny pubs 144 May 26 11:59 -rw-rw-r-1 jenny pubs 104 May 28 11:44 -rwxrw-r-1 jenny pubs 85 May 6 08:27 drwxrwxr-x 2 jenny pubs 32 Oct 6 22:56 drwxrwxr-x 16 jenny pubs 1296 Jun 6 17:33 The a (all) option lists all files, including invisible ones. $ ls a . .profile .. bin

bin c calendar execute letters shell

c calendar

execute letters

shell

Combining the a and l options displays a long listing of all the files, including invisible files, in the working directory. Thus list is still in alphabetical order.

LINUX LAB MANUAL

24

LINUX OPERATING SYSTEM MANUAL $ ls -al total 12 drwxrwxr-x drwxrwx---rw-rw-r-drwxrwxr-x drwxrwxr-x -rw-rw-r--rw-rw-r-drwxrwxr-x drwxrwxr-x

ENGR. JULIUS S. CANSINO

6 26 1 2 2 1 1 2 16

jenny jenny jenny jenny jenny jenny jenny jenny jenny

pubs 480 root 816 pubs 161 pubs 80 pubs 144 pubs 184 pubs 85 pubs 32 pubs 1296

Jun Jun Jun May Mar May May Oct Jun

6 6 6 20 26 28 6 6 6

17:42 14:45 17:15 09:17 11:59 11:44 08:27 22:56 17:33

. .. .profile bin c calendar execute letters shell

mkdir
Syntax: mkdir [option] directory-list The mkdir utility creates one or more directories. You must have permission to write to and search (execute permission) the parent directory you are creating. The mkdir utility creates directories that contain the standard invisible entries . (representing the directory itself) and .. (representing the parent directory). The following command creates a directory named accounts as a subdirectory of the working directory and a directory named prospective as a subdirectory of accounts. $ mkdir -- parents accounts/prospective Below, without changing working directories, the same user creates another subdirectory within the accounts directory: $ mkdir accounts/existing Next, the user changes the working directory to the accounts directory and creates one more subdirectory: $ cd accounts $ mkdir closed The last example shows the user creating another subdirectory. This time the mode option removes all access permissions for group and others. $ mkdir mode go = accounts/past_due

LINUX LAB MANUAL

25

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

rmdir
Syntax: rmdir directory-list The rmdir utility deletes empty directories from the filesystem by removing links to those directories. Refer to the rm utility with the r option if you need to remove directories that are not empty together with their contents. The following command line deletes the empty literature directory from the working directory: $ rmdir literature The next command line removes the letters directory using an absolute pathname: $ rmdir /home/jenny/letters

mv
Syntax: mv existing-file-list directory You can use the mv(move) utility to move files from one directory to another. However, the mv utility is actually more general than that it can be used to change the pathname of a file as well as changing the simple filename. If the working directory is /home/alex, Alex can use the following command to move the files names and temp from the working directory to the literature directory: $ mv names temp literature This command changes the absolute pathname of names and temp from /home/alex/names and /home/alex/temp to /home/alex/literature/names and /home/alex/literature/temp. Like most other Linux commands, mv accepts either absolute or relative pathnames.

LINUX LAB MANUAL

26

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

pwd
Syntax: pwd file-list-directory The pwd utility displays the full pathname of the current directory. The following shows the pathname of the directory literature. $ cd /home/alex/literature $ pwd /home/alex/literature $ cd $ pwd /home/alex

LINUX LAB MANUAL

27

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

Supplementary Exercises 2
A. Directions: Identify the following by writing AP for absolute pathname, RP for relative pathname or SF for simple filename. ____ 1. milk_co ____ 2. correspond/business/milk_co ____ 3. /home/alex ____ 4. /home/alex/literature/promo ____ 5. .. ____ 6. letter.0610 ____ 7. /home/jenny/draft ____ 8. classic.txt ____ 9. games/mario ____ 10. /home/joey/love B. Directions: Perform and write the command given the series of operations. Note: You are in your home directory. 1. Make a subdirectory in your home directory named Private. Command: ____________________________________________________ 2. Confirm that the directory exists using ls. It must have a / after its name. Command: ____________________________________________________ 3. Create another directory named Public. Command: ____________________________________________________ 4. Change the directories into Private. Command: ____________________________________________________ 5. Confirm your location. Command: ____________________________________________________ Output: (pathname) ________________________________________________ 6. Ask for a listing of files. Command: ____________________________________________________ 7. Create a new file in the Private directory named secrets using cat. Command: ____________________________________________________ 8. Enter the text Linux is fun. Enjoy using Linux!!! and quit by going to a new line and pressing Ctrl+D. Command: ____________________________________________________

LINUX LAB MANUAL

28

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

9. Once you are back at the shell, list the contents of the directory. Command: ____________________________________________________ Output: 10. Return to your home directory Command: ____________________________________________________ 11. From your home directory, list the contents of the Private directory. Command: ____________________________________________________ Output:

LINUX LAB MANUAL

29

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

Experiment No. 3

STANDARD INPUT AND OUTPUT


OBJECTIVES 1. to give the importance of redirection and piping in files 2. to use the redirection and piping symbols in manipulating the output and input to/from a file DISCUSSION A standard output is a place to which it can send information, frequently text. The command never knows where the information it sends to standard output is going. The information can go to a printer, an ordinary file, or a terminal. The Terminal as Standard Input and Standard Output When you first log in, the shell directs your commands standard output to the device file that represents your terminal. Directing output causes it to appear on your terminals screen. The shell directs standard input to come from the same file that your commands receive anything you type on your terminal keyboard as input. REDIRECTION The term redirection encompasses the various ways you can cause the shell to alter where a commands standard input comes from or where standard output goes to. Redirecting Standard Output The redirect output symbol(>) instructs the shell to redirect a commands output to the specified file instead of to the terminal.

file shell Standard Input command Standard Output

LINUX LAB MANUAL

30

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

The format of a command line that redirects output is Command [arguments] > filename Where command is any executable program, arguments are optional arguments and filename is the name of the ordinary file the shell redirects the output to. Caution: If the file already exists, the shell will overwrite it and destroy its contents. Example: Cat with its output redirected $ cat > sample.txt This text is being entered at the keyboard. Cat is copying it to a file. Press CONTROL-D to indicate the End of File. CONTROL-D Another example shows how to use cat and the redirect output symbol to concatenate (join one after the other) several files into a one larger file. The first three commands display the content of the three files: stationery, tape and pens. For this case, the standard output is redirected to the supply_orders. The final cat command shows that supply_orders contains the content of all three files. $ cat stationery 2000 sheets letterhead ordered: 10/7/97 $ cat tape 1 box of masking tape ordered: 10/14/97 5 boxes filament tape ordered: 10/28/97 $ cat pens 12 doz. Black pens ordered: 10/4/97 $ cat stationery tape pens > supply_orders $ cat supply_orders 2000 sheets letterhead ordered: 10/7/97 1 box of masking tape ordered: 10/14/97 5 boxes filament tape ordered: 10/28/97 12 doz. Black pens ordered: 10/4/97 $

LINUX LAB MANUAL

31

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

Redirecting Standard Input The redirect input symbol (<) instructs the shell to redirect a commands input from the specified file instead of the terminal. The format of a command line that redirects input is Command [arguments] < filename Where command is any executable program, arguments are optional arguments and filename is the name of the ordinary file the shell redirects the output to. Giving a cat command with input redirected from a file yields the same result as giving a cat command with the filename as an argument.

file shell Standard Input command Example: cat with its input redirected $ cat supply_orders 2000 sheets letterhead ordered: 10/7/97 1 box of masking tape ordered: 10/14/97 5 boxes filament tape ordered: 10/28/97 12 doz. Black pens ordered: 10/4/97 $ Standard Output

PIPES
The shell uses a pipe to connect standard output of one command directly to standard input of another command. A pipe has the same effect as redirecting standard output of one command to a file and then using that file as standard

LINUX LAB MANUAL

32

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

input to another command. It does away with separate commands and the intermediate file. The symbol for a pipe is a vertical bar ( | ). The syntax of a command line using a pipe is Command_a [arguments] | command_b [arguments] This command line uses a pipe to generate the same result as the following group of command lines: Command_a [arguments] > temp Command_b [arguments] < temp rm temp The command using the pipe is not only easier to type, it is generally more efficient than the sequence of three commands because it does not create a temporary file. Significance of Pipes 1. It eliminates temporary files. 2. It allows two commands to operate synchronously. As soon as the first command creates some output, the second can begin execution. Example: Using a temporary file to store intermediate results $ who > temp $ sort < temp alex tty1 Aug 8 19:49 alex ttyp0 Aug 10 06:23 jenny tty2 Aug 8 19:50 jenny ttyp1 Aug 8 19:51 (:1.0) scott ttyp2 Aug 10 07:09 (bravo) $ rm temp Example: A pipe doing the work of a temporary file $ who | sort alex tty1 Aug 8 19:49 alex ttyp0 Aug 10 06:23 jenny tty2 Aug 8 19:50 jenny ttyp1 Aug 8 19:51 (:1.0) scott ttyp2 Aug 10 07:09 (bravo) $

LINUX LAB MANUAL

33

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

Supplementary Exercises 3
A. Directions: Write the command to perform the following using pipe ( | ). 1. Taking standard input from standard output of who and using a pipe to redirect standard output to standard input of lpr through sort. Command: _____________________________ 2. Redirect the standard output from sort command into a file named phone_list. Assume the input file is named as numbers. Command: _____________________________ B. Directions: Type the contents of the following files book1, book2 and book3. a. Write the series of operation to join the contents of the files Book1, Book2 and Book3 respectively, placed in a file named BookofLove. b. Write the series of operation to concatenate the contents of the files Book1, Book2 and Book3 respectively, stored in a file named LibroNgPuso using pipe (|).

Book1
You are the one I so adore our love, romance, passion and amour; You are the one who shows me charm embraces me in your loving arms;

Book2
You are the one who reads to me in fun, serious and poetry; You are the I love to kiss in morning, night, and daytime bliss;

LINUX LAB MANUAL

34

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

Book3
You are the one that I cherish without your love I would perish; You are the one who shares the light soul-mate bonded, all day, all night; You are the one, the one you are , my childrens dad, my shining star.

LINUX LAB MANUAL

35

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

Experiment No. 4

DATA SELECTION COMMANDS


OBJECTIVES 1. to use cut and grep utility in selecting a specific part or string in a file 2. to compare the function of cut and grep utility in manipulating files. DISCUSSION Data is often arranged in columns in a file. Columns of information, rather than lines, can also be extracted from a file using the cut utility. However, if we often need to locate lines that contain words or a specific series of characters called strings or pattern in a file we can use the grep utility.

cut
Syntax: cut [option] [file-list] The cut utility selects characters or TAB separated fields from lines of input and writes them to standard output. Characters and fields are numbered starting with 1. The file-list is a list of ordinary files. If omitted, cut reads from standard input. For the following two examples, assume that the - l option produces the following output in the working directory. $ ls l total 148 -rwxrwxrwx -rwxrw-r- -rw-rw-r- -rwxrw-r- -rw-rw-rw-rw-rw-rw-rwxrw-r- -

1 1 1 1 1 1 1

alex alex root alex alex alex alex

group 123 Jun 31 1997 group 2065 Aug 16 14:48 root 72 May 24 11:44 group 715 Mar 2 16:30 group 14 Jan 8 1997 group 14 Jan 8 1997 group 218 Nov 27 1996

countout headers memo memos_save tmp1 tmp2 typescript

The command below outputs the permissions of the files in the working directory. The cut utility with the c option specifies that characters 2 through 10 be selected from each input line. The characters in this range are written to standard output. LINUX LAB MANUAL 36

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

$ ls l | cut c2-10 total 148 rwxrwxrwx rwxrw-r- rw-rw-r- rwxrw-r- rw-rw-rwrw-rw-rwrw-rw-r- The next command outputs the size and name of each file in the working directory. This time the f option is used with the cut command to select the fifth and ninth fields from the input lines. The d option tells cut that SPACEs, not TABs, delimit fields in the input. The tr command with the s option is necessary so that sequences of more than one SPACE character are combined into a single SPACE; otherwise, cut counts the extra SPACE characters as separate fields. $ ls l | tr s | cut -fs.9 d 123 countout 2065 headers 72 memo 715 memos_save 14 tmp1 14 tmp2 218 typescript The last example uses cut to display a list of full names as stored in the fifth field of the /etc/passwd file. The d option specifies that the colon character be used as the field delimeter. $ cat /etc/passwd root: KUvM/SVhXd9HQ:0:0:Root:/:/bin/sh jenny:KcDO6q80sjJjs:401:50:Jenny Chen:/home/jenny:/bin/zsh alex:edJigJPVhC55k:402:50:Alex Watson:/home/alex:/bin/bash scott:md:eOmvImaC.M:504:500:Scott Adams:/home/scott:/bin/tcsh hls:Ud2Ih60BN1crk:505:500:Helen Simpson:/home/hls:/bin/bash $ cut d: -fS /etc/passwd Root Jenny Chen Alex Watson Scott Adams Helen Simpson

LINUX LAB MANUAL

37

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

grep
Syntax: grep [option] pattern [file-list] The grep utility searches one or more files, line by line, for a pattern can be a simple string or another form of a regular expression. The grep utility takes various actions, specified by options, each time it finds a line that contains a match for the pattern. The grep utility takes its input from files you specify on the command line or from standard input. The pattern is a regular expression. You must quote regular expressions that contain special characters, SPACEs, or TABs. An easy way to quote these characters is to enclose the entire expression within single quotation marks. The file-list contains pathnames of ordinary text files that grep searches. $ grep 'fred' /etc/passwd This command searches for all occurrences of the text string 'fred' within the "/etc/passwd" file. It will find and print (on the screen) all of the lines in this file that contain the text string 'fred', including lines that contain usernames like "fred" - and also "alfred". $ grep '^fred' /etc/passwd This command searches for all occurrences of the text string 'fred' within the "/etc/passwd" file, but also requires that the "f" in the name "fred" be in the first column of each record (that's what the caret character tells grep). Using this more-advanced search, a user named "alfred" would not be matched, because the letter "a" will be in the first column. $ grep 'joe' * This command searches for all occurrences of the text string 'joe' within all files of the current directory. We can use grep as either a filter or to look inside files. It also uses regular expressions.

LINUX LAB MANUAL

38

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

Let's start off with using grep to look inside files. If I wanted to determine which users use the bash shell, I could do it the following way:

grep "/bin/bash" /etc/passwd

We could pipe this grep output to the cut or the sort commands, etcetera. We can search any file, or group of files looking for various patterns. Remember that grep is looking for a pattern, so as per our example, it's not looking for a string, it's looking for a pattern beginning with a forward slash ( / ), followed by the letters 'b' i 'n', followed by another forward slash ( / ), etc. Understand that it's searching for a pattern. Why am I emphasising this? Primarily, because we could use our pattern matching characteristics. We could say: grep "[hH][aA][Mm]" /etc/passwd

which would match all of the following patterns: hAM HaM HAm

I could also: grep "Linuz" bazaar.txt

We could equally have done a grep "Linu." bazaar.txt

or better still grep '[lL]inu.' bazaar.txt

LINUX LAB MANUAL

39

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

which would've grep'd using a pattern 'l' or 'L', i, 'n', 'u' and then any other character. This would grep both Linux and Linus (or linux or linus). You can see a similarity starting to appear between using regular expressions in grep and regular expressions in sed. They are all RE's, so there should be no difference! For example I can combine these patterns now: grep "[Ll]inu." bazaar.txt

What happens if I wanted any 5 characters to follow Linu or linu, then I would use the following: grep "[Ll]inu.\{5\}" bazaar.txt

grep (naturally) has other switches that are useful: switch action -B 5 -A 3 -v -n display the context - i.e. 5 lines of context before a match display the context - 3 lines of context after a match reverses the pattern label every line

The following command would grep every line except the lines that have the pattern Linus/linus/Linux/linux etc. and it would label every line because of the -n switch. grep -vn "[Ll]inu." bazaar.txt

If you wanted to grep on a whole stack of files then you could: grep -n "Linux." *

which would show you the filename and the line number of the line that contains the pattern. So far we have used grep fairly effectively to look inside a file or a series of files. Now we want to use grep as a filter.

LINUX LAB MANUAL

40

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

The best way to see how this works is to use your messages file (/var/log/messages). This file logs all messages from applications on system. If you don't have access to your messages file, then you need to be logged in as root. In order to affect this particular example, you need to have access to the /var/log/messages file.[12] Look at the time on your system with the following command: date

Use grep as a filter to extract all messages that occurred during 11 'o clock in the morning. The following pattern should achieve this: tail -20 /var/log/messages |grep '11:[0-5][0-9]'

In this case, we're using grep as a filter, filtering the input that's coming from the tail command and actually reducing the amount of output we receive. Now clearly, because of the ability to pipe commands, you can use the output of one grep command as input to the next. So we start off with a huge amount of data, but by piping data through grep we filter out only the information that we want. To continue our examples, let us count the number of lines that exist in the messages file. cat /var/log/messages |wc -l

Now count the number of messages that occurred at 11 o' clock? cat /var/log/messages |grep '11:[0-5]\{2\}'

Now count the number of messages that occurred at 11 o' clock on 25 November: cat /var/log/messages |grep '11:[0-5][0-9]' |grep 'Nov 25'

You should notice fewer lines displayed as your pattern gets more specific. LINUX LAB MANUAL 41

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

We could keep on filtering as many times as we want. What I encourage you to do, is to look for a pattern and, using a pattern, reduce the number of output lines. By reducing output lines to fit your criteria, you can save on time. We could use grep with ls: cd /var/log

Let's only look for files that are directories: ls -la |grep '^d'

Let's only look for files that are not directories: ls -la |grep -v '^d'

Let's look for files that end in 'log': ls -la |grep -v '^d' |grep 'log$'

You see how we are using grep as a filter for the ls command. grep is one of the "Swiss army knives" that you just cannot do without. The more we script the more we will use grep and the better we will get at it.

LINUX LAB MANUAL

42

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

Supplementary Exercises 4
Directions: 1. Use the editor to create a file named test-g containing the lines below about mother 7ab About the cat t -2 ab ^a line t$ 1234 ttt he at brother (leave a blank space here) at aBc t5t 15-23 They are at v Lyle Strand (leave a blank space here) tat a -2 b (leave a blank space here) 2. Enter the following basic grep command line then write the output and your observation. a. $ grep ab test-g Output:

Explanation:

b. $ grep he test-g Output:

LINUX LAB MANUAL

43

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

Explanation:

c. $ grep v ab test-g Output:

Explanation:

d. $ grep t.t test-g Output:

Explanation: e. $ grep ^a test-g Output:

Explanation: f. $ grep \^a test-g Output:

Explanation: g. $ grep t$ test-g

LINUX LAB MANUAL

44

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

Output:

Explanation: h. $ grep n ^$ test-g Output:

Explanation:

3. Entering the following commands separately and observe the output. Is there any difference between these two command lines? What are these (if any)? a. $ grep Lyle Strand test-g b. $ grep Lyle Strand test-g | more Explanation:

4. Try entering $ grep lyle test-g. What is the output? What happened? Output: 5. Differentiate the output of these two command lines: $ grep i He test-g and $ grep He test-g. Explanation:

6. Create a new file called names.tmp. Use TAB to separate the fields rather than spaces. 101 102 104 106 107 Nate John Cassy Mary Isaac H. M. T. L. C.

LINUX LAB MANUAL

45

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

7. Create a second file called numbers.tmp, again with fields separated by TAB characters. 101 104 105 106 555-9136 551-1191 511-1972 317-6512

8. Enter the following commands then write the output and explanation. a. $ cut f2 names.tmp Output:

Explanation: b. $ cut f1 numbers.tmp Output:

Explanation: c. $ cut c1-3 numbers.tmp Output:

Explanation:

LINUX LAB MANUAL

46

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

Experiment No. 5

DATA REFINEMENT COMMANDS


OBJECTIVES 1. to sort the contents of the file 2. to join together lines from two or more files 3. to remove lines that occur repeatedly in a file 4. to identify the different data refinement commands such as sort, join and unique DISCUSSION A field is a sequence of characters on a line in an input file. These sequences are bounded by blanks or by a blank and the beginning or end of the line. These fields are used to define sort fields. A sort field is a sequence of characters that sort uses to put lines in order. A sort field can contain part or all of one or more fields in the input file. Example: Fields and sort fields Field Joey Field Dedel Field 12345

sort
Syntax: sort [options][field-specifier-list][file-list] The sort utility sorts and/or merges one or more text files in sequence. When you use the n option, sort performs a numeric sort. Example: $ cat days Monday Tuesday Wednesday Thursday Friday Saturday Sunday

LINUX LAB MANUAL

47

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

$ sort days Friday Monday Saturday Sunday Thursday Tuesday Wednesday You can instruct sort to skip any number of fields and characters on a line before beginning its comparison. Blanks normally separate one field from another. The next example has +1 argument which indicates that sort is to skip one field beginning its comparison. It skips the first-name field. $ sort list Alice MacLeod 94114 David Mack 94114 Jack Cooper 94072 Janet Demspy 94111 Richard MacDonald 95510 Tom Winstrom 94201 Toni Barnett 95020 $ sort +1 list Toni Barnett 95020 Jack Cooper 94072 Janet Demspy 94111 Richard MacDonald 95510 Alice MacLeod 94114 David Mack 94114 Tom Winstrom 94201 In the previous example, MacLeod comes before Mack. After finding that the two line were the same through the third letter, sort put L before K, because it arranges lines in order of ASCII character codes, in which upper case letters comes before lowercase. The f option makes sort treat uppercase and lowercase letters as equals and thus fixes the problem with MacLeod and Mack. $ sort f +1 list Toni Barnett Jack Cooper Janet Demspy 95020 94072 94111

LINUX LAB MANUAL

48

LINUX OPERATING SYSTEM MANUAL Richard MacDonald 95510 David Mack 94114 Alice MacLeod 94114 Tom Winstrom 94201

ENGR. JULIUS S. CANSINO

The b option causes sort to ignore leading spaces. With the b option, the zip codes come out in proper order. When sort determines that MacLeod and Mack have the same zip codes, it compares the entire lines, putting Alice MacLeod before David Mack. $ sort b +2 list Jack Cooper 94072 Janet Dempsey 94111 Alice MacLeod 94114 David Mack 94114 Tom Winstrom 94201 Toni Barnett 95020 Richard MacDonald 95510

join
Syntax: join [file-list][file-list] The join utility is used to relationally join two files. Example: File1 contains the following: aaa 111 bbb 555 ccc 666 eee 444 zzz 333 File2 contains the following: aaa 111 bbb 555 ccc 666 eee 444 fff 222 zzz 333

LINUX LAB MANUAL

49

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

$ join File1 File2 aaa 111 111 bbb 555 555 ccc 666 666 eee 444 444 zzz 333 333

uniq
Syntax: uniq [options][input-file][output-file] The uniq utility displays a file, removing all but one copy of successive repeated lines. If the file has been sorted, uniq ensures that no two lines that it displays are the same. Example: $ cat test boy took bat home boy took bat home girl took bat home dog brought hat home dog brought hat home dog brought hat home Without any options uniq displays only one copy if successive repeated lines. $ uniq test boy took bat home girl took bat home dog brought hat home The -- count option displays the number of consecutive occurrences of each line in the file. $ uniq -- count test 2 boy took bat home 1 girl took bat home 3 dog brought hat home

LINUX LAB MANUAL

50

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

The -- repeated option displays only lines that are consecutively repeated in the file. $ uniq --repeated test boy took bat home dog brought hat home The --unique option displays only lines that are not consecutively repeated in the file. $ uniq --unique test girl took bat home

LINUX LAB MANUAL

51

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

Supplementary Exercise 5
Directions: Illustrate the output of the following operations and explain what happened. 1. sort test1 Output:

Explanation:

2. sort test4 Output:

Explanation: 3. sort +1 2 test1 Output:

Explanation:

4. sort m test1 test2

LINUX LAB MANUAL

52

LINUX OPERATING SYSTEM MANUAL Output:

ENGR. JULIUS S. CANSINO

Explanation:

5. sort Output:

Explanation:

6. join test5 test6 Output:

Explanation:

7. uniq test8 Output:

Explanation:

8. uniq test9 Output: Explanation:

LINUX LAB MANUAL

53

LINUX OPERATING SYSTEM MANUAL The files are as follows: test1 aaa 111 bbb 555 zzz 333 ccc 666 eee 444 test2 aaa:111 bbb:555 zzz:333 ccc:666 eee:444 test3 aaa 111 zzz 333 eee 444 bbb 555 ccc 666 test4 aaa 111 aaa:111 bbb 555 bbb:555 zzz 333 ccc 666 eee 444 zzz:333 ccc:666 eee:444

ENGR. JULIUS S. CANSINO

test5 aaa 111 bbb 555 zzz 333 ccc 666

LINUX LAB MANUAL

54

LINUX OPERATING SYSTEM MANUAL eee 444 fff 222 test6 aaa 111 bbb 555 ccc 666 eee 444 zzz 333 test7 aaa 111 bbb 555 ccc 666 eee 444 fff 222 zzz 333 test8 aaa 111 aaa 111 aaa 111 bbb 555 bbb 555 zzz 333 ccc 666 eee 444 test9 aaa 111 aaa 111 bbb 555 bbb 555 aaa 111 zzz 333 ccc 666 eee 444 aaa 111

ENGR. JULIUS S. CANSINO

LINUX LAB MANUAL

55

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

Experiment No. 6

FILE PERMISSION
OBJECTIVES 1. to determine the permissions various kinds of users are granted for files 2. change permissions for a file 3. examine how permissions limit access to a specific file DISCUSSION FILE PERMISSIONS Three types of users can access a file: the owner of the file(owner), a member of a group to which the owner belongs(group), and everyone else(other). A user can attempt to access an ordinary file in three ways: by trying to read from, write to or execute it. Three types of users, each able to access a file in three ways gives a total of nine ways to access an ordinary file. The three types of permissions that can be granted to Linux files are symbolized by r read permission w write permission x execute permission When you call ls, ls displays a line of information about the file, $ ls l letter -rw-r--r-- 1 joey pogi 14344 Nov 2 10:52 letter

e.g.

From left to right, the line contains the following information: the type of file the files access permissions(the next nine characters) the number of links to the file the name of the owner of the file the name of the group that has group access to the file the size of the file in characters(bytes) the date and time the file was created or last modified the name of the file The next nine characters after the file type are the permission modes of the file. The first three characters define the owner permission modes. The next three characters define the group permission modes. The last three characters define the others permission modes.

LINUX LAB MANUAL

56

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

Thus, for file file2.test -rw-rw---- 1 stud01 unxclass 4905 Sep 26 19:09 file2.test

the following are true: The owner can read and write to the file. The group members can read and write to the file. Others have no access permission to the file. Note: If a directory has an x permission, users are given access to that directory. A directory with permissions drwxr---- still cannot be accessed by members of the group. The correct permission mode is drwxr-x--. Changing Permission Modes To change the access permission modes of files, issue the chmod command.

Chmod
Syntax: chmod [options] who operation permission file-list The chmod command changes the access mode of a file. It changes the ways in which a file can be accessed by the owner of the file, the group to which the file belongs, and/or all other users. Only the owner of a file or the Superuser can change the access mode, or permissions, of a file. There are two ways of accomplishing this: 1. Symbolic Mode The class of the user is designated by one or more of the following letters: Letter U G O A User Class User Group Other All Meaning Owner of the file Group to which the owner belongs All other users Can be used in place of u, g, and o

LINUX LAB MANUAL

57

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

The operation to be performed is defined by the following list: Operator + = Meaning Adds permission for the specified user class Removes permission for the specified user class Sets permission for the specified user resets all other permissions for that user class

Examples: The following command gives all users execute permission for file: chmod +x file The following command removes read and write permission for group and others from file. chmod go rw file The following command gives other users read and write permission for file. chmod o+rw file The following command gives read permission to group and others. chmod g+r, o+r file 2. Absolute Mode In place of the symbolic method of changing the access permissions for a file, you can use an octal number to represent the mode. Examples: The following command gives all users read, write and execute permission for file, chmod 777 file The following command gives read and write permission to all users for file. chmod 666 file

LINUX LAB MANUAL

58

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

The following command gives read and write permission to the owner of file only. chmod 600 file The Linux system access permission scheme and lets you give other users access to the files you want to share and keep your private files confidential. But there is an exception to the access permissions described above. The user who knows the root password can log in as the Superuser and have a full access to all files, regardless of owner or access permissions. The following examples show how to use the chmod utility change permissions on a file named temp. The initial access mode of temp is shown by the command ls. $ ls l temp -rw-rw-r-- l

cha

pubs 57

Jul

10

14:20 temp

The command line below removes all access permissions for the group and all other users, so that only the owner has the access to the file. When you do not follow an equal sign with a permission, chmod removes all permissions for the specified user class. The ls utility verifies the change. $ chmod go= temp $ ls l temp -rw------- l cha

pubs 57

Jul

10

14:20 temp

The next command changes the access modes for all users to read and write. Now anyone can read from or write to the file. Again, ls utility verifies the change. $chmod a=rw temp $ ls l temp -rw-rw-rw- l cha

pubs 57

Jul

10

14:20 temp

Using absolute mode, the a=rw becomes 666. The next command performs the same functions as the previous command.

LINUX LAB MANUAL

59

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

Supplementary Exercises 6
Directions: 1. Create a file named pmode using an editor. 2. Type the content of the file. The Linux operating system was and is being developed through the cooperation of many, many people around the world: It is the product of the Internet. It is also a FREE operating system. Linux is a UNIX work-alike: Someone who is used to using UNIX will be right at home with Linux. Linux is more efficient, in many cases faster, and has more advanced development tools. 3. Perform the operations below using the initial access mode of the file. 4. Write the sequence of commands to execute the following operations in two permission modes ( symbolic and absolute ). 5. Write the output in using the ls utility to verify the changes. Example: The owner can read the file. Command: Symbolic: $ chmod o=r pmode Absolute: $ chmod 400 pmode Output: -r-------l cha pubs 40

Jul

10

14:20 pmode

1. Give all users permission to execute the file Command: Symbolic: Absolute: Output:

___________________________________ ___________________________________

___________________________________________________________________

2. Give read and write permission to the group only. Command: Symbolic: Absolute: Output:

___________________________________ ___________________________________

___________________________________________________________________

LINUX LAB MANUAL

60

LINUX OPERATING SYSTEM MANUAL


3. Give all users read permission for file.

ENGR. JULIUS S. CANSINO

Command: Symbolic: Absolute: Output:

___________________________________ ___________________________________

___________________________________________________________________

4. Remove read and write permission for file to others. Command: Symbolic: Absolute: Output:

___________________________________ ___________________________________

___________________________________________________________________

5. Grant yourself the right to write changes to files. Command: Symbolic: Absolute: Output: ___________________________________ ___________________________________

___________________________________________________________________

6. Owner, group and public can read, write and execute files. Command: Symbolic: Absolute: Output:

___________________________________ ___________________________________

___________________________________________________________________

7. Owner can read, write and execute; group and public can read and execute file. Command: Symbolic: ___________________________________ Absolute: ___________________________________ Output:
___________________________________________________________________

8. Owner can read, write and execute; group and public can execute file. Command: Symbolic: ___________________________________ Absolute: ___________________________________ Output:
___________________________________________________________________

LINUX LAB MANUAL

61

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

9. Owner can read and write; group and public can read file. Command: Symbolic: ___________________________________ Absolute: ___________________________________ Output:
___________________________________________________________________

10. Owner can read and write, group can read and public has no access to file. Command: Symbolic: ___________________________________ Absolute: ___________________________________ Output:
___________________________________________________________________

LINUX LAB MANUAL

62

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

Experiment No. 7 OBTAINING USER AND SYSTEM INFORMATION & COMMUNICATING WITH OTHER USERS
OBJECTIVES 1. to establish communication with other users in a network using write and talk commands 2. to obtain user and system information using w, who and finger commands DISCUSSION If you are running Linux on a network, you may find out who is using the computer system and how it is running. You can use several utilities that vary in the details they provide and options they support. The oldest utility, who, produces a short list of names along with the terminal connection each person is using and the time the person logged onto the system.

who
The who utility displays a list of the users currently logged in. Below, you can see the first column of who shows the Alex and Jenny are logged in. (Each appears twice because each is running a second login shell inside the X Window System graphical user interface.) The second column shows the designation of the terminal that each person is using. The third column shows the date and time the person logged in. The final column, when present, identifies either the X display that is being used or the name of the remote computer where the person is logged in: $ who alex alex jenny jenny

tty1 ttyp0 tty2 ttyp0

Aug 2 05:55 Aug 2 05:55 (x) Aug 2 05:56 Aug 2 05:56 (:1.0)

The information that who displays is useful if you want to communicate with someone at your installation. If the person is logged in, you can use write or talk to establish communication immediately. If who does not show that the person is logged in, or if you do not need to communicate immediately, you can send that person Linux system mail. If you need to find out which terminal you are using or what time you logged in, you can use the command who am i: $ who am i

LINUX LAB MANUAL

63

LINUX OPERATING SYSTEM MANUAL speedy!alex ttyp0 Aug 7 05:55 (x)

ENGR. JULIUS S. CANSINO

finger
The finger utility displays the login names of the users, together with their full names, terminal device numbers, the times they logged in, and other information. You can use finger to display a list of the people who are currently using the system. In addition to login names, finger supplies each users full name, along with information about which terminal line the person is using, how recently the user typed something on the keyboard, when the user logged in, and information about where the user is located (if the terminal line appears in a system database). If the user has logged in over the network, the name of the remote system is shown as the users location. The (*) in front of the name of Helens terminal (TTY) line indicates that she has blocked others form sending messages directly to her terminal. $ finger Login Name jenny Jenny Chen jenny Jenny Chen alex Alex Watson alex Alex Watson hls Helen Simpson

Tty 2 pl 1 p0 *p2

Idle 13:25 4:00 13:26 7

Login Aug 2 Aug 2 Aug 2 Aug 2 Aug 2

Time 05:56 05:56 05:55 05:55 19:17

Office [ :1.0 ] [x] [ bravo ]

Office Phone

Another use of the finger utility $ finger alex Login: alex Name: Alex Watson Directory: /home/alex On since wed Aug 7 05:55 (call) on tty1, idle 13:39 On since wed Aug 7 05:55 (PDT) on ttyp0 from x Mail last read Wed Aug 7 19:31 1996 (PDT) Plan: I will be at a conference in Hawaii all next week. If you need to see me, contact Jenny Chen, x1693 You can also use finger to learn more about a particular individual by specifying more information on the command line. Alex is currently logged in and actively using his terminal (if he were not, finger would report how long he had been idle). You also learn form finger that if you want to set up a meeting with Alex, you should contact Jenny at extension 1693. The information shown after heading Plan: however, was supplied by Alex. The finger utility searched for a file named .plan in Alexs home directory and displayed its contents. You may find it helpful to create a .plan file yourself; it can contain any information you

LINUX LAB MANUAL

64

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

choose, such as you typical schedule, interest, phone number, or address. If Alex had not been logged in, the finger utility would have reported the last time he had used the system. If you do not know a persons login name, you can use the finger utility to learn it, For example, you might know that Helens last name is Simpson, but you might not guess that her login name is hls. The finger utility can also search for information on Helen using her first or last name. The following commands find the information on Helen using her first or last name. The following commands find the information you seek, along with information on other users on the system whose names are Helen or Simpson. The finger utility is not case sensitive. $ finger helen Login: hls . . $ finger simpson Login: hls . .

Name: Helen Simpson

Name: Helen Simpson

w
The w utility displays a list of the users currently logged in. The first column w displays shows that Alex, Jenny, and Scott are logged in. The second column shows the designation of the terminal that each person is using. The third column shows where each person is logged in (that is, which X displays or remote computer); some versions of w do not show this column. The fourth column shows the date and time each person logged in. The fifth column indicates how long each person has been idle (that is, how many minutes have elapsed since the last key was pressed on the keyboard). The next two columns give measures of how much computer processor time each person has used during the current login session and on the task that is currently running. The last column show the command each person is currently running. $w 8:20am up 4 days, 2:28, 6 users, load average: 0.04, 0.04, 0.00 User tty from login@ idle JCPU PCPU what alex tty1 5:55am 13:45 alex ttyp0 5:55am 27 2:55 1 -zsh jenny tty2 5:56am 13:44 jenny ttyp1 :1.0 5:56am 3 nvi 36tmp.txt scott ttyp2 bravo 7:17pm 1 w

LINUX LAB MANUAL

65

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

The first line that the w utility displays includes the current time of the day, how long he computer has been running (in days, hours, and minutes), how many users are logged in, and how busy the system is (load average). The three load average numbers represent the number of jobs waiting to run, averaged over the past minute, 5 minutes and 15 minutes. The information that w displays is useful if you want t communicate with someone at your installation. If the person is logged in and recently active, you can use write or talk to establish communication immediately. If w does not show that the person is logged in, or if you do not need to communicate immediately, you can send that person Linux system mail. COMMUNICATING WITH OTHER USERS These utilities allow you to exchange messages and files with other users either interactively or not.

write
You can use the write utility to send a message to another user who is logged in. When the other user also uses write to send you a message, you establish two-way communication. When you give a write command, it displays a banner on the other users terminal saying that you are about to send a message. The syntax of a write command line is write destination-user [terminal] The destination-user is the login name of the user you want to communicate with. The terminal is the optional terminal name. You can find out the login and terminal names of the users who are logged in by using who, w, or finger. To establish two-way communication with another user, you and the other user must each execute write, specifying the others login name as the destination-user. The write utility then copies text, line by line, from one terminal to the other. Example: Starting to write to Alex $ write alex Hi Alex, are you there? o Alex and Jenny have established a convention: Type o (for over) when you are ready for the person to type and type oo (for over and out) when you are

LINUX LAB MANUAL

66

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

ready to log off. You can use this convention, another convention, or none at all. When you want to stop communicating with other user, press CONTROL-D at the beginning of a line. Pressing CONTROL-D tells write to quit, displays EOF (End Of File) on the other users terminal, and returns you to the shell. The other user must do the same. Example: Alex responding with write $ write Alex Hi Alex are you there? o Message from alex@speedy on ttyp3 at 8:20 Yes Jenny, Im here. o

talk
You can use the talk utility to carry on a two-way conversation with another person who is logged in on your system. If your system is connected to a network, you can also use talk to communicate with someone on a different computer. When you use talk, your screen is split into two sections; once you establish contact with the other person are displayed in the bottom half. In this example, Alex needs some information from Jenny: $ talk jenny Alexs display is immediately split into two sections, and the following message appears at the top of his screen: [Waiting for your party to respond] Meanwhile, this message appears on Jennys screen and she responds: Message from Talk_Daemon@bravo at 9:22 talk: connection requested by alex@bravo. talk: respond with: talk alex@bravo $ talk alex@bravo Alex and Jenny are both using a computer named bravo; alex@bravo is Alexs network address. Below shows what Jennys and Alexs screens look like as they type their messages. Alexs screen: [Connection established] Did you finish the slides for for the 9:30 meeting today? Sounds good, see you in a few minutes! Jennys screen: [Connection established] Hi, Alex, whats up? Yes, theyre all set. Should I just meet you in the conference room?

LINUX LAB MANUAL

67

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

To end the talk session, one person interrupts by pressing CONTROL-D, and the following message appears before a new shell prompt is displayed: [Connection closing. Exiting] If you see the following message when you try to use talk to reach someone, the mesg command has been used to block the interruptions (see the next section): [Your party is refusing messages] Before the talk was available, people used the write command to interact with each other on the same computer. The talk utility has a few advantages over write; With the talk the other persons messages appear on your screen, letter by letter, as they are typed; write, on the other hand, sends only a whole line at a time. If you use write, sometimes you are not sure whether the other person is still connected at the other end (or is just a slow typist). Also, unlike write, talk has been extended to support communication over the network. Still, if you need to exchange a quick message with another person logged in on your system, with out disrupting your current screen display, you may want to use write instead.

LINUX LAB MANUAL

68

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

Supplementary Exercises 7
Directions: 1. Using who utility, write the names of the users currently logged in, together with their terminal device numbers, the times they logged in.

2. Using w utility and using w utility with its s options, differentiate the output. What do you think is the use of the s option added to w utility?

3. Experiment on how you are going to display the information of a specific user. Write the syntax below.

4. Establish a two-way communication between you and one of your classmates using the write or talk utility. Call your teacher to check if you have set up already conversation by showing your messages on your display terminals.

LINUX LAB MANUAL

69

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

Experiment No. 8

The vi Editor
OBJECTIVES 1. to familiarize the environment of the vi editor 2. to create and access files using the vi editor DISCUSSION Before vi was developed, the standard UNIX system editor was ed. The ed editor was line oriented, which made it difficult to see the context of your editing. Then ex came along ex was a superset of ed. The most notable advantage that ex had over ed was display editing facility that allowed users to work with a full screen of text instead of working only a line at a time. While you were using ex, you could use the display editing facility by giving the ex command vi(for visual mode). The vi editor (short for visual editor) is a screen editor which is available on almost all Linux systems. Once you have learned vi, you will find that it is a fast and powerful editor. vi has no menus but instead uses combinations of keystrokes in order to accomplish commands. If you are just beginning to learn Linux, you might find the Pico editor easier to use (most command options are displayed at the bottom of the screen). The vi editor is not a text formatting program. It does not justify margins, center titles, or provide the output formatting features of a sophisticated word processing system.

Starting vi
Start vi with the following command line to create a file named practice: $ vi practice When you press RETURN, the command line disappears. The tildes (~) indicates that the file is empty. They go away as you add lines to the file. If your screen looks like a distorted, your terminal type is probably not set correctly. If you start vi with an incorrect terminal type, press ESCAPE and then give the following command to exit from vi and get the shell prompt back: :q! When you enter the colon (:), vi moves the cursor to the bottom line of the screen. The characters q! tell vi to quit without saving your work.

LINUX LAB MANUAL

70

LINUX OPERATING SYSTEM MANUAL Command and Input Modes

ENGR. JULIUS S. CANSINO

Two of the vi editors modes of operation are Command Mode and Input Mode. While vi is in Command mode, you can give vi commands. For example, in Command Mode you can delete text or exit from vi. You can also command vi to enter Input Mode. In Input Mode vi accepts anything you enter as text and displays it on the screen. Press ESCAPE to return vi to Command Mode. The vi editor does not normally keep you informed about which mode it is in. The following command causes vi to display the mode it is in while you are entering text or commands: : set showmode The colon(:) in this command puts vi into another mode, Last Line Mode. While in this mode, vi keeps the cursor on the bottom line of the screen. When you enter the colon, vi moves the cursor to last line. Finish the command by pressing RETURN. There are three types of Input Modes: OPEN, INSERT and APPEND. When giving vi a command, it is important to bear in mind that the editor is case sensitive. The vi editor interprets the same letter as two different commands, depending on whether you enter an uppercase or lowercase character. Beware of the key that causes your keyboard to send only uppercase characters; it is typically labeled CAPSLOCK or SHIFTLOCK. If you set this key to enter uppercase text while you are in Input Mode and then you exit to Command Mode, vi interprets your commands as uppercase letters. It can be very confusing when this happens because vi does not appear to be the following the commands you are giving it.

Entering Text To begin entering text in an empty file, you must first change from the command mode to the insert mode. To do this, type the letter i. When you start typing, anything you type will be entered into the file. Type a few short lines and hit Return at the end of each of line. Unlike word processors, vi does not use word wrap. It will break a line at the edge of the screen. If you make a mistake, you can use the Backspace key to remove your errors. If the Backspace key doesn't work properly on your system, try using the Ctrl h key combination.

LINUX LAB MANUAL

71

LINUX OPERATING SYSTEM MANUAL Cursor Movement

ENGR. JULIUS S. CANSINO

You must be in command mode if you wish to move the cursor to another position in your file. If you've just finished typing text, you're still in insert mode and will need to press ESC to return to the command mode. Moving One Character at a Time Try using your direction keys to move up, down, left and right in your file. Sometimes, you may find that the direction keys don't work. If that is the case, to move the cursor one character at the time, you may use the h, j, k, and l keys. These keys move you in the following directions: h j left one space down one space l k right one space up one space

If you move the cursor as far as you can in any direction, you may see a screen flash or hear a beep. Moving among Words and Lines While these four keys (or your direction keys) can move you just about anywhere you want to go in your file, there are some shortcut keys that you can use to move a little more quickly through a document. To move more quickly among words, you might use the following: w b e moves the cursor forward one word moves the cursor backward one word (if in the middle of a word, b will move you to the beginning of the current word). moves to the end of a word.

To build on this further, you can precede these commands with a number for greater movement. For example, 5w would move you forward five words; 12b would move you backwards twelve words. [You can also use numbers with the commands mentioned earlier. For example, 5j would move you down 5 characters.] Command Keys and Case You will find when using vi that lower case and upper case command keys are interpreted differently. For example, when using the lower case w, b, and e commands, words will be defined by a space or a punctuation mark. On the other hand, W, B, and E commands may be used to move between words also, but these commands ignore punctuation.

LINUX LAB MANUAL

72

LINUX OPERATING SYSTEM MANUAL Shortcuts

ENGR. JULIUS S. CANSINO

Two short cuts for moving quickly on a line include the $ and the 0 (zero) keys. The $ key will move you to the end of a line, while the 0 will move you quickly to the beginning of a line. Screen Movement To move the cursor to a line within your current screen use the following keys: H M L moves the cursor to the top line of the screen. moves the cursor to the middle line of the screen. moves the cursor to the last line of the screen. To scroll through the file and see other screens use: ctrl-f ctrl-b ctrl-u ctrl-d scrolls down one screen scrolls up one screen scrolls up a half a screen scrolls down a half a screen

Two other useful commands for moving quickly from one end to the other of a document are G to move to the end of the file and 1G to move to the beginning of the file. If you precede G with a number, you can move to a specific line in the document (e.g. 15G would move you to line 15). Moving by Searching One method for moving quickly to a particular spot in your file is to search for specific text. When you are in command mode, type a / followed the text you wish to search for. When you press Return, the cursor will move to the first incidence of that string of text. You can repeat the search by typing n or search in a backwards direction by using N. Basic Editing To issue editing commands, you must be in command mode. As mentioned before, commands will be interpreted differently depending upon whether they are issued in lower or upper case. Also, many of the editing commands can be preceded by a number to indicate a repetition of the command.

LINUX LAB MANUAL

73

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

Deleting (or Cutting) Characters, Words, and Lines To delete a character, first place your cursor on that character. Then, you may use any of the following commands: x X dw dd D deletes the character under the cursor. deletes the character to the left of your cursor. deletes from the character selected to the end of the word. deletes all the current line. deletes from the current character to the end of the line.

Preceding the command with a number will delete multiple characters. For example, 10x will delete the character selected and the next 9 characters; 10X will delete the 10 characters to the left of the currently selected character. The command 5dw will delete 5 words, while 4dd deletes four lines. Pasting Text using Put Often, when you delete or cut text, you may wish to reinsert it in another location of the document. The Put command will paste in the last portion of text that was deleted since deleted text is stored in a buffer. To use this command, place the cursor where you wish the deleted text to appear. Then use p to reinsert the text. If you are inserting a line or paragraph use the lower case p to insert on the line below the cursor or upper case P to place in on the line above the cursor. Copying Text with Yank If you wish to make a duplicate copy of existing text, you may use the yank and put commands to accomplish this function. Yank copies the selected text into a buffer and holds it until another yank or deletion occurs. Yank is usually used in combination with a word or line object such as the ones shown below: yw yy copies a word into a buffer (7yw copies 7 words) copies a line into a buffer (3yy will copy 3 lines)

Once the desired text is yanked, place the cursor in the spot in which you wish to insert the text and then use the put command (p for line below or P for line above) to insert the contents of the buffer.

LINUX LAB MANUAL

74

LINUX OPERATING SYSTEM MANUAL Replacing or Changing Characters, Words, and Lines

ENGR. JULIUS S. CANSINO

When you are using the following commands to replace text, you will be put temporarily into insert mode so that you can change a character, word, line, or paragraph of text. r R cw replaces the current character with the next character you enter/type. Once you enter the character you are returned to command mode. puts you in overtype mode until you hit ESC which will then return you to command mode. changes and replaces the current word with text that you type. A dollar sign marks the end of the text you're changing. Pressing ESC when you finish will return you to command mode.

Inserting Text If you wish to insert new text in a line, first position the cursor to the right of where you wish the inserted text to appear. Type i to get into insert mode and then type in the desired text (note that the text is inserted before the cursor). Press ESC to return to command mode. Inserting a Blank Line To insert a blank line below the line your cursor is currently located on, use the o key and then hit ESC to return to the command mode . Use O to insert a line above the line the cursor is located on. Appending Text You can use the append command to add text at any place in your file. Append (a) works very much like Insert (i) except that it insert text after the cursor rather than before it. Append is probably used most often for adding text to the end of a line. Simply place your cursor where you wish to append text and press a. Once you've finished appending, press ESC to go back to command mode. Joining Lines Since vi does not use automatic word wrap, it is not unusual in editing lines to end up with lines that are too short and that might be improved if joined together. To do this, place your cursor on the first line to be joined and type J. As with other commands, you can precede J with a number to join multiple lines (4J joins 4 lines).

LINUX LAB MANUAL

75

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

Undoing Be sure to remember this command. When you make a mistake you can undo it. DO NOT move the cursor from the line where you made the change. Then try using one of the following two commands: u U undoes the last change you made anywhere in the file. Using u again will "undo the undo". undoes all recent changes to the current line. You can not have moved from the line to recover the original line.

Closing and Saving Files When you edit a file in vi, you are actually editing a copy of the file rather than the original. The following sections describe methods you might use when closing a file, quitting vi, or both. Quitting and Saving a File The command ZZ (notice that it is in uppercase) will allow you to quit vi and save the edits made to a file. You will then return to a Unix prompt. Note that you can also use the following commands: :w :q :wq to save your file but not quit vi (this is good to do periodically in case of machine crash!). to quit if you haven't made any edits. to quit and save edits (basically the same as ZZ).

Quitting without Saving Edits Sometimes, when you create a mess (when you first start using vi this is easy to do!) you may wish to erase all edits made to the file and either start over or quit. To do this, you can choose from the following two commands: :e! :q! reads the original file back in so that you can start over. wipes out all edits and allows you to exit from vi.

More about Combining Commands, Objects, and Numbers

Now that you've learned some basic vi commands you might wish to expand your skills by trying some fancy combination steps. Some commands are generally used in combination with a text object. We've already seen some examples of this. For example, when you use the command dw to delete a word,

LINUX LAB MANUAL

76

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

that combines the delete (d) command with the word (w) text object. When you wish to delete multiple words, you might add a number to this combination. If you wished to delete 2 words you might use 2dw or d2w. Either of these combinations would work. So, as you can see, the general format for a command can be (number) (command) (text object) or (command) (number) (text object). You might wish to try out some of the following combinations of commands and objects: Command Text Object d (delete) w (word to the left) y (yank/copy) b (word to the right or backward) c (change) e (end of word) H (top of the screen) L (bottom of the screen) M (middle of the screen) 0 (zero - first character on a line) $ (end of a line) ( (previous sentence) ) (next sentence) [ (previous section) ] (next section) Repeating a Command If you are doing repetitive editing, you may wish to use the same command over and over. vi will allow you to use the dot (.) to repeat the last basic command you issued. If for example, you wished to deleted several lines, you could use dd and then . (dot) in quick succession to delete a few lines. A Quick Word about Customizing Your vi Environment There are several options that you can set from within vi that can affect how you use vi. For example, one option allows you to set a right margin that will then force vi to automatically wrap your lines as you type. To do this, you would use a variation of the :set command. The :set command can be used to change various options in vi. In the example just described, you could, while still in vi, type :set wrapmargin=10 to specify that you wish to have a right margin of 10. Another useful option is :set number. This command causes vi to display line numbers in the file you are working on. Other Options To view a listing of other options, you could type :set all. To view only those options which are currently in effect, you can type set: by itself. Options that you set while in a vi session will apply during that session only. To make

LINUX LAB MANUAL

77

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

permanent changes to your vi environment, you could edit your .exrc file. However, you should not edit this file unless you know what you are doing!

Useful vi Commands Exercise 8


Cut/Paste Commands x delete one character (destructive backspace) dw delete the current word (Note: ndw deletes n numbered words) dd delete the current line (Note: ndd deletes n numbered lines) D delete all content to the right of the cursor d$ same as above :u undo last command p,P paste line starting one line below/above current cursor location J combine the contents of two lines "[a-z]nyy yank next n lines into named buffer [a-z] "[a-z]p/Pplace the contents of selected buffer below/above the current line Extensions to the Above Commands :3,18d 16,25m30 23,29co62 delete lines 3 through 18 move lines 16 through 25 to after line 30 copy specified lines and place after line 62

Cursor Relocation Commands :[n] shift g h/l/j/k ^f/^b ^u/^d $ 0 goto line [n] place cursor on last line of text move cursor left, right, down and up move forward, backward in text, one page move up, down one half page move to end of line move to beginning of line

Extensions to the Above Commands b e ( ) move backwards one word (Note: nb moves back n number of words) move to end of current word move to beginning of curent block move to the end of current block

LINUX LAB MANUAL

78

LINUX OPERATING SYSTEM MANUAL Searching and Substitution Commands

ENGR. JULIUS S. CANSINO

/ [string] search forward for string ? [string] search backwards for string n repeat last search N repeat search in opposite direction cw change the contents of the current word, (use ESC to stop replacement mode) c$ replace all content to the right of cursor (exit replacement mode with ESC) c0 replace all content to the left of cursor (exit with ESC) :1,$s/s1/s2/g (Yow!) global replacement of string1 with string2 r replace current character with next character typed Entering the Insert Mode i I a A o/O ESC Begin inserting text at current cursor location Begin inserting text at the beginning of the current line Begin appending text, one character to the right of current cursor location Begin appending text at the end of the current line Begin entering text one line below\above current line Exit insertion mode and return to command mode

Exiting and Entering VI ZZ :wq :e! :q :w Fancy Stuff :1,10w file :340,$w>>file :sh ^d :![command] :r![command] :r[filename] :$r newfile :r !sort file write lines 1 through 10 to file newfile write lines 340 through the end of the file and append to file newfile escape temporarily to a shell return from shell to VI execute UNIX command without leaving VI read output of command into VI read filename into VI read in newfile and attach at the end of current document read in contents of file after it has been passed through the UNIX sort save file and exit VI same as above return to last saved version of current file quit without save, (Note :q! is required if changes have been made) write without exit (:w! to force write)

LINUX LAB MANUAL

79

LINUX OPERATING SYSTEM MANUAL :n :^g :set number :set showinsert :set all :set ai

ENGR. JULIUS S. CANSINO

^T ^D :set tabstop=n >> <<

open next file (works with wildcard filenames, ex: vi file*) list current line number show line numbers show flag ("I") at bottom of screen when in insert mode display current values of VI variables set autoindent; after this enter the insert mode and tab, from this point on VI will indent each line to this location. Use ESC to stop the indentations. set the autoindent tab one tab stop to the right set the autoindent tab one stop to the left sets default tab space to number n shift contents of line one tab stop to the right shift contents of line one tab stop to the left

LINUX LAB MANUAL

80

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

Experiment No. 9

BASIC SYSTEM ADMINISTRATION


OBJECTIVES 1. To enumerate the basic procedures in adding groups, users and passwords to Linux systems. 2. To give the importance of passwords in secured computer system. DISCUSSION One person is often designated as the system administrator. On large systems this can be a full-time job. On smaller systems a user of the system may be assigned to do system administration in addition to his or her other work. On personal systems you are your own system administrator. The system administrator has access to certain system wide powers that are beyond those of ordinary users. Some commands, such as commands that halt the system, should be executed only by the system administrator. Read and write file access permissions do not affect the system administrator. However, the system administrator cannot execute a file that does not have the execute bit set. The system administrator can search any directory and create a file in or remove a file from any directory. The system administrator can also read from, write to, or execute any file. Some restrictions and safeguards that are built into some commands do not apply to the system administrator. For example, the system administrator can change any users password without knowing the old password. Because these powers affect the security of all users files as well as the security of the entire system, there is a special login name and password for the user who can log in on the system to perform these functions. The login name is generally root. Although you can set up a Linux system with any name in place of root, it is not advisable to do so. Many programs depend on this name being root. There is also a special term for the user who has logged in as root; this user is called the Superuser. Frequently, the system administrator logs in as root to have permissions to perform necessary tasks. Under Linux, every file and program must be owned by a user. Each user has a unique identifier called userID(UID). Each user must also belong to at least one group, a collection of users. Users may belong to multiple groups. Like users, groups also have unique identifiers called groupIDs (GIDs).

LINUX LAB MANUAL

81

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

Each users right can be defined in one of two ways: a normal user and a root user. Normal User can access only what they own or given permission to run. Root user can access all files and programs in the system, whether or not root owns them. The root user is often called the Superuser. More than a login name is required for a user to be able to log in and use the system. A user must have the necessary files, directories, and optionally a password to log in. Regardless of how you add a user, you must make sure every user has a password. Unless you are on a single-user system, security dictates a password for each user. Password can help prevent unauthorized users from logging in on your system. If your system is on a network, passwords are even more important. Passwords are a firstline of defense in keeping a system secure.

Useradd
The useradd utility allows you to add new user accounts to your system quickly and is the most convenient utility if you need to add user accounts often. By default, useradd assigns the next highest unused user ID (UID) to the new account and uses /bin/sh as the users login shell. Adding Users 1. Log-on as root. 2. From the #prompt, type useradd username Example: If you want to add user joey, you should type useradd joey. After using useradd to create an account, you can give the user a password with the passwd utility, using the users name as an argument. Because you are logged in as the Superuser, passwd does not ask you for the old password, even if there is one.

Passwd
The passwd utility allows you to change a password. Depending on the versions of Linux you are using, the messages the passwd utility presents and the sequence of the interaction may differ slightly. Given the command passwd(followed by a return) in response to the shell. This command causes the shell to execute the passwd utility. The first item passwd asks you for is your old password(it skips this question if you do not have a password yet). The passwd utility verifies this password to ensure that an

LINUX LAB MANUAL

82

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

unauthorized user is trying to alter your password. Next, passwd requests the new password. Your password must meet the following criteria: It must be at least six characters long. A password must have characters from at least two of the following three classes: uppercase letters, lowercase letters, and digits. It cannot be too similar to your login name. After you enter your new password, passwd asks you to retype it to make sure you did not make a mistake when you entered it. If the new password is the same both times you enter it, your password is changed. If the passwords differ, it means that you made an error in one of them; passwd displays the following message: They dont match; try again. New password: Example: $ passwd joey Changing password for joey Enter old password: Enter new password: Re-type new password: Password changed. $ Putting Passwords to Users 1. From the $prompt, type passwd username. IT IS VERY IMPORTANT THAT YOU INCLUDE THE username BECAUSE TYPING passwd ALONE WILL CHANGE THE root PASSWORD! Example: If you want to put a password for user joey, you will type passwd joey. 2. You will be asked to type your password, then Linux will ask you again to type the password for verification. Remember: Always take good care of the root account . When someone gains root access, he gains control of your Linux machine. Make passwords you could easily understand while hard for others to guess.

LINUX LAB MANUAL

83

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

Many password-cracking tools are basing their cracks on random guessing of passwords based on dictionary words. If possible regularly change you password. Caution: Dont think that you can make an easy to-guess passwords for regular users since they are just regular users. Some hackers gain root access through backing regular users account first and then from there get the root account.

groupadd
The groupadd utility allows you to add a group from the current list of groups from your system. Adding Groups 1. Log-on as root. 2. From the #prompt, type groupadd groupname Example: If you want to add the group CpEStud, you should type , groupadd CpEStud. Note: If you want to know more about a Linux command or if you know what utility you want to use but have forgotten exactly how to use it, use the man utility. The man utility allows you to view one screenful of information about a certain command or utility. To use, give the command man followed by the name of the utility. Example: $ man who

LINUX LAB MANUAL

84

LINUX OPERATING SYSTEM MANUAL

ENGR. JULIUS S. CANSINO

Supplementary Exercises 9
Directions: 1. Create two groups in your terminal, one as RegUsers while the other one will be named Supervisors. 2. Add users. Users are you and your groupmates. Also add the name of your teacher as mother users. 3. Add to group RegUsers your group members usernames. Then, add the username of your teacher to group Franzen. 4. Your teacher will check your work afterwards.

LINUX LAB MANUAL

85

Potrebbero piacerti anche