Quick viewing(Text Mode)

Fundamentals of Linux

Fundamentals of Linux

Fundamentals of

Student Workbook Fundamentals of Linux

Fundamentals of Linux

Jeff Howell

Published by ITCourseware, LLC., 7245 South Havana Street, Suite 100, Centennial, CO 80112

Contributing Authors: Mark Copley, Rob Roselius

Editor: Rick Sussenbach

Assistant Editor: Jan Waleri

Special thanks to: Many instructors whose ideas and careful review have contributed to the quality of this workbook, including Larry Burley and Richard Raab, and the many students who have offered comments, suggestions, criticisms, and insights.

Copyright © 2008 by ITCourseware, LLC. All rights reserved. No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photo-copying, recording, or by an information storage retrieval system, without permission in writing from the publisher. Inquiries should be addressed to ITCourseware, LLC., 7245 South Havana Street, Suite 100, Centennial, Colorado, 80112. (303) 302-5280.

All brand names, product names, trademarks, and registered trademarks are the property of their respective owners.

Page ii Rev 3.1.2 © 2008 ITCourseware, LLC Fundamentals of Linux

Contents

Chapter 1 - Course Introduction ...... 11 Course Objectives ...... 12 Course Overview ...... 14 Using the Workbook ...... 15 Suggested References ...... 16

Chapter 2 - Getting Started ...... 19 What is UNIX? ...... 20 A Brief History of UNIX ...... 22 Linux ...... 24 The Toolkit Philosophy ...... 26 Linux Distributions ...... 28 and Open Source Movements ...... 30 Logging In ...... 32 Logging Out ...... 34 Try a Few More Commands ...... 36 Changing Your Password ...... 38 Online Documentation - man Pages ...... 40 Online Documentation - info Pages ...... 42 Labs ...... 44

Chapter 3 - The File System - Files ...... 47 What is a File? ...... 48 The ls Command ...... 50 The cat Command ...... 52 The more and less Commands ...... 54 The head and tail Commands ...... 56 Copy, Rename, and Delete: cp, mv, rm ...... 58 File Names ...... 60 Working with MS-DOS disks: mtools ...... 62 Labs ...... 64

© 2008 ITCourseware, LLC Rev 3.1.2 Page iii Fundamentals of Linux

Chapter 4 - The File System - Directories ...... 67 Hierarchical File System ...... 68 Pathnames ...... 70 pwd and cd - Navigating Directories ...... 72 mkdir and rmdir - Managing Directories ...... 74 The cp Command (again) - Copy Files ...... 76 Two Useful Directory Names - . and ...... 78 Labs ...... 80

Chapter 5 - Text Editors ...... 83 Linux Text Editors ...... 84 The pico Editor ...... 86 The Nedit Editor ...... 88 The ...... 90 The vi Text Editor Family ...... 92 Labs ...... 94

Chapter 6 - Editing With vi ...... 97 What is vi? ...... 98 Getting Started - vi Buffering ...... 100 Command Mode and Insert Mode ...... 102 Getting Started ...... 104 Moving the Cursor Around ...... 106 Inserting Text ...... 108 Deleting a Character or Line ...... 110 Undo Last Command ...... 112 Opening a New Line ...... 114 Save Your Work or Abort the Session ...... 116 Review of vi Commands ...... 118 Labs ...... 120

Chapter 7 - Personal Utilities ...... 123 The date Utility ...... 124 The bc Utility ...... 126 The cal Utility ...... 128

Page iv Rev 3.1.2 © 2008 ITCourseware, LLC Fundamentals of Linux

The id Utility ...... 130 The uname Utility ...... 132 The finger Utility ...... 134 The script Utility ...... 136 The clear Utility ...... 138 The at and crontab Utilities ...... 140 Labs ...... 142

Chapter 8 - Text Handling Utilities ...... 145 The grep Utility ...... 146 The tr Utility ...... 148 The cut Utility ...... 150 The sort Utility ...... 152 The wc Utility ...... 154 The diff Utility ...... 156 The lpr Utility ...... 158 Labs ...... 160

Chapter 9 - File System Security ...... 163 File Permissions ...... 164 The chmod Utility ...... 166 Directory Permissions ...... 168 The umask Command ...... 170 The chown, chgrp, and su Commands ...... 172 Labs ...... 174

Chapter 10 - File System Management Utilities ...... 177 The find Utility ...... 178 The df Utility ...... 180 The du Utility ...... 182 Compressing Files ...... 184 The ln Utility ...... 186 The ulimit Utility ...... 188 The tar Utility ...... 190 Labs ...... 192

© 2008 ITCourseware, LLC Rev 3.1.2 Page v Fundamentals of Linux

Chapter 11 - Communication Utilities ...... 195 The write and talk Utilities ...... 196 The mesg Utility ...... 198 Mail Overview ...... 200 The mail Utility ...... 202 Other Email Options ...... 204 IRC: Internet Relay Chat ...... 206 Labs ...... 208

Chapter 12 - Networking Utilities ...... 211 Remote Login with telnet ...... 212 Remote File Transfer With ftp ...... 214 Secure Login With ssh ...... 216 Secure File Transfer With scp ...... 218 Text-Based Web Access with lynx ...... 220 Web Access with wget and curl ...... 222 Samba Server Overview ...... 224 The smbclient Utility ...... 226 NFS File Sharing Overview ...... 228 Labs ...... 230

Chapter 13 - Using the ...... 233 What is a Shell? ...... 234 The Command Line ...... 236 Standard Input, Standard Output, and Standard Error ...... 238 Using Default Standard In and Standard Output ...... 240 I/O Redirection ...... 242 I/O Redirection - Examples ...... 244 I/O Redirection - Warning ...... 246 Appending Output of a File ...... 248 Pipes ...... 250 The tee Utility ...... 252 Labs ...... 254

Page vi Rev 3.1.2 © 2008 ITCourseware, LLC Fundamentals of Linux

Chapter 14 - Filename Generation ...... 257 Filename Generation ...... 258 The ? Special Character ...... 260 The * Special Character ...... 262 The [ ] Special Characters ...... 264 The ! Special Character ...... 266 Labs ...... 268

Chapter 15 - Processes ...... 271 What is a Process? ...... 272 Process Structure ...... 274 The ps Utility ...... 276 Options to the ps Utility ...... 278 Background Commands (&) ...... 280 Killing Background Processes ...... 282 Redirecting the Standard Error ...... 284 Labs ...... 286

Chapter 16 - Shell Programming Concepts ...... 289 What is a Shell? ...... 290 Which Shell? ...... 292 What is a Shell Script? ...... 294 Why Use Shell Scripts? ...... 296 Labs ...... 298

Chapter 17 - Flow Control ...... 301 The Exit Status of Commands ...... 302 Command Line Examples ...... 304 The test Command ...... 306 The if-then-else Construct ...... 308 The elif Construct ...... 310 A Loop Example ...... 312 Labs ...... 314

© 2008 ITCourseware, LLC Rev 3.1.2 Page vii Fundamentals of Linux

Chapter 18 - Variables ...... 317 User Created Variables ...... 318 The read Command ...... 320 The Shell Environment ...... 322 The export Command ...... 324 Subshells ...... 326 Command Substitution ...... 328 Quoting Mechanisms ...... 330 Shell Arithmetic ...... 332 Assigning Variables - Summary ...... 334 Labs ...... 336

Chapter 19 - Special Variables ...... 339 Command-Line Arguments ...... 340 $# - Number of Arguments ...... 342 The shift Command ...... 344 $* - All Arguments ...... 346 $$ - PID of Shell ...... 348 Labs ...... 350

Chapter 20 - More Flow Control...... 353 The for Loop ...... 354 Example ...... 356 The while Loop ...... 358 The case Construct ...... 360 Labs ...... 362

Chapter 21 - X Windows and Desktops ...... 365 The X Window System ...... 366 Using X ...... 368 Window Managers and Desktops ...... 370 The Gnome Desktop ...... 372 The KDE Desktop ...... 374 Applications: The GIMP ...... 376 Applications: OpenOffice ...... 378 Applications: Web Browsers ...... 380

Page viii Rev 3.1.2 © 2008 ITCourseware, LLC Fundamentals of Linux

Appendix A - More Editing With vi ...... 383 Scrolling the Buffer ...... 384 Cursor Motion Commands - w,W,b,B,e,E ...... 386 Cursor Motion Commands - $,^,0,G ...... 388 Cursor Motion Commands - f,t,F,T ...... 390 Delete Operator - ...... 392 Change Operator - ...... 394 Yank Operator - y ...... 396 Put Commands - p,P ...... 398 Searching for a Pattern - /,n,N,? ...... 400 The Join Command ...... 402 The file Command - :f ...... 404 Edit File Command - :e ...... 406 Cut and Paste Between Files ...... 408 Read File Command - : ...... 410 Set Options Command ...... 412 Set Options Command - .exrc file ...... 414 Labs ...... 416

Appendix B - Bash Shell Features ...... 419 Viewing Your Command History ...... 420 Editing and Re-executing Commands ...... 422 Aliases ...... 424

Solutions ...... 427

Glossary ...... 449

Index ...... 453

© 2008 ITCourseware, LLC Rev 3.1.2 Page ix Fundamentals of Linux

Page x Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 1 Course Introduction

Chapter 1 - Course Introduction

© 2008 ITCourseware, LLC Rev 3.1.2 Page 11 Fundamentals of Linux

Course Objectives

 Manage files and directories by creating, copying, renaming, removing, editing, and performing other operations on them.

 Create and modify files using the vi editor.

 Use many Linux utilities for text file manipulation, personal workspace management, file system management, and communication with other users.

 Take advantage of Linux security mechanisms to protect files and programs from unauthorized access and to configure shared access among work groups.

 Use the Linux shell (command interpreter) to control the flow and processing of data through pipelines.

 Increase your productivity by generating file names using "wild card" pattern matching.

 Look up commands and other information in the online Linux reference manuals.

 Explain the purpose of shell programs.

 Recognize applications for shell programs.

 Design and write shell programs of moderate complexity.

 Manage multiple concurrent processes to achieve higher utilization of Linux.

Page 12 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 1 Course Introduction

© 2008 ITCourseware, LLC Rev 3.1.2 Page 13 Fundamentals of Linux

Course Overview

 Audience: This course is designed for users who are new to Linux. Since this is intended to be a first course in Linux, "users" refers to application users, , system administrators, help desk staff, documenters, testers, managers, and anyone else who will be using Linux daily or occasionally.

Note: The above list is not in any particular order!

 Prerequisites: We assume that you have used a computer before and have a basic understanding of how to interact with one.

 Student Materials:

 Student Workbook

 Classroom Environment:

 Linux system with one terminal per student.

Page 14 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 1 Course Introduction

Using the Workbook

This workbook design is based on a page-pair, consisting of a Topic page and a Support page. When you lay the workbook open flat, the Topic page is on the left and the Support page is on the right. The Topic page contains the points to be discussed in class. The Support page has code examples, diagrams, screen shots and additional information. Hands On sections provide opportunities for practical application of key concepts. Try It and Investigate sections help direct individual discovery.

In addition, there is an index for quick look-up. Printed lab solutions are in the back of the book as well as on-line if you need a little help.

The Topic page provides The Support page has the main topics for class- additional information, room discussion. examples and suggestions.

Java Servlets Chapter 2 Servlet Basics Code examples are in a Hands On: The Servlet Life Cycle fixed font and shaded. The

 The servlet container controls the life cycle of the servlet. Add an init() method to your Today servlet that initializes a bornOnonline date, then file print thename bornOn date is listed along with the current date:  When the first request is received, the container loads the servlet class above the shaded area. Today.java and calls the init() method. Topics are organized into ...  For every request, the container uses a separate thread to call  the service() method. public class Today extends GenericServlet { first ( ), second ( ) and private Date bornOn; public void service(ServletRequest request, third () levelWhen points. the servlet is unloaded, the container calls the destroy() ServletResponse response) throws ServletException, IOException method. { ...  // Write the document As with Java’s finalize() method, don’t count on this being Callout boxesout.println("This point out servlet was born on " + bornOn.toString()); called. out.println("It is now " + today.toString()); important }parts of the  init() public void init() { Override one of the methods for one-time initializations, instead of bornOn = new Date(); using a constructor. example} code. The init() method is } called when the servlet is loaded into the container.  The simplest form takes no parameters.

public void init() {...}

 If you need to know container-specific configuration information, use the other version.

public void init(ServletConfig config) {...

 Whenever you use the ServletConfig approach, always call the superclass method, which performs additional initializations.

super.init(config);

Screen shots show Page 16 Rev 2.0.0 © 2002 ITCourseware, LLC © 2002 ITCourseware, LLCexamples ofRev 2.0.0 what you Page 17 Pages are numbered should see in class. sequentially throughout the book, making lookup easy.

© 2008 ITCourseware, LLC Rev 3.1.2 Page 15 Fundamentals of Linux

Suggested References

Berners-Lee and Mark Fischertti. 1999. Weaving the Web - The Original Design and Ultimate Destiny of the World Wide Web. HarperBusiness, New York, NY. ISBN 006251587X.

Dalheimer, Matthias Kalle and Matt Welsh. 2005. Running Linux, Fifth Edition. O’Reilly & Associates, Sebastapol, CA. ISBN 0596007604.

Nemeth, Evi, Garth Snyder and Trent R. Hein. 2006. Linux System Administration Handbook, Second Edition. Prentice Hall, Upper Saddle River, NJ. ISBN 0131480049.

Siever, Ellen, et al. 2005. Linux in a Nutshell, Fifth Edition. O’Reilly & Associates, Sebastapol, CA. ISBN 0596009305.

Torvald, Linus and David Diamond. 2002. Just for Fun - The Story of an Accidental Revolutionary. HarperBusiness, New York, NY. ISBN 0066620732.

Williams, Sam. 2002. Free As In Freedom - Richard Stallman's Crusade for Free Software. O’Reilly & Associates, Sebastapol, CA. ISBN 0596002874.

Page 16 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 1 Course Introduction

© 2008 ITCourseware, LLC Rev 3.1.2 Page 17 Fundamentals of Linux

Page 18 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 2 Getting Started

Chapter 2 - Getting Started

Objectives

 Provide a high-level overview of the background of UNIX and Linux.

 Explain the relationship between UNIX and Linux.

 Log in and out of the system.

 Run a few commands.

 Change your password.

 Look up commands in the on-line Linux reference manuals.

© 2008 ITCourseware, LLC Rev 3.1.2 Page 19 Fundamentals of Linux

What is UNIX?

 UNIX is a general purpose, multi-tasking, multi-user, interactive, scalable, computer .

 HP-UX, SunOS, Solaris, AIX, SCO UNIX, System V.4, etc., are all versions of UNIX.

Why UNIX?

 In the 1980s, UNIX became commercially popular for several reasons:

 Customer demand for the benefits of open systems:

 Application portability

 Vendor independence

 Connectivity and interoperability in multivendor environments

 User portability

 New workstation hardware could be brought to market more quickly with an existing operating system.

 Major vendors (such as Sun, DEC, HP, IBM) implemented UNIX- based product lines.

 UNIX provides excellent networking capabilities.

Page 20 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 2 Getting Started

UNIX is an operating system (OS), not a programming language. It supports software development in almost all languages, such as C, C++, Java, COBOL, Pascal, FORTRAN, BASIC, Smalltalk, LISP, etc. It is also widely used in client/server configurations, as the OS that supports server applications.

© 2008 ITCourseware, LLC Rev 3.1.2 Page 21 Fundamentals of Linux

A Brief History of UNIX

AT&T Bell Labs UNIX 1970 UNIX invented as a pet Version 3 project by Ken Thomson. Version 4 1975 Microsoft founded. Version 6 1977 UNIX, rewritten in C, ported to various hardware. Xenix Version 7 BSD 1980 Xenix introduced. 1981 MS-DOS introduced. 1982 Sun Microsystems founded. System V 1984 AT&T releases System V. SVR2 SVR3 BSD 4.3 1980s UNIX market growth and fragmentation.

SVR4 1989 SVR4 introduced. 1991 Linux invented. World Wide Web invented. 1993 Windows NT launched. 1994 Java invented.

 UNIX was originally written at Bell Laboratories in 1970.

 In the mid-1970s, the University of California at Berkeley began making additions and enhancements to UNIX.

 In the early 1980s, AT&T began offering support for AT&T System III UNIX.

 In 1989, AT&T released System V, Release 4 (SVR4).

 SVR4 merged features of System V, BSD, and Xenix.

 Sun used SVR4 as the basis of Solaris.

Page 22 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 2 Getting Started

UNIX was originally designed and written by Ken Thompson for the purpose of aiding in computer science research. AT&T provided UNIX source code at a low cost to many universities, including the University of California At Berkeley (UCB). Berkeley UNIX, built upon the Sixth Edition, added, over the years, many utilities, such as vi and csh; it was distributed under the name BSD (Berkley Software Distribution). Much research and development was done in the areas of file systems and networking. The history is well documented in several books, such as: McKusick, Marshall Kirk, et. al. 1996. The Design and Implementation of the 4.4BSD UNIX Operating System. Addison-Wesley, Reading, MA. ISBN 0201549794.

AT&T, in 1982, merged several internal versions of UNIX and began licensing UNIX to vendors, such as Hewlett-Packard. In 1985, AT&T began shipping UNIX System V, and committed to support it and maintain backward compatibility in future versions of UNIX.

In 1989, AT&T's UNIX System Labs released System V, Release 4 (SVR4). SVR4 merged features of System V, BSD, and Microsoft's Xenix.

The diagram on the facing page is oversimplified with respect to the number of actual versions and variants of UNIX and its relatives, and with respect to the cross-influencing that the various versions have had on each other.

© 2008 ITCourseware, LLC Rev 3.1.2 Page 23 Fundamentals of Linux

Linux

 In 1991, Linus Torvalds began writing his own UNIX-like operating system kernel, while studying an academic UNIX variant called Minix.

 Working on a 386 PC using the GNU C compiler (which he ported to Minix), he posted his source code on the Internet.

 Other programmers began contributing to this new, free operating system, which Linus named Linux.

 Linux itself is the operating system kernel, which includes:

 Basic bootstrap code  Kernel routines (process scheduling, memory mgt., etc.)  Hardware device drivers (disk, sound, video, network, etc.)  File system drivers

 To make a Linux system useful, you'll install your choices from among the thousands of freely available (or commercial) programs.

 GNU software (UNIX utilities, development tools, etc.)  User command-line shells (bash, ksh, etc.)  Network servers (Apache httpd, WU ftpd, Sendmail, etc.)  Graphical User Interfaces (Gnome, KDE, AfterStep, etc.)  Office applications (Netscape, StarOffice, etc.)

 You can download the latest Linux kernel source code from a variety of locations.

 To install and run it, you must compile the kernel, set up a filesystem, install the kernel, build the programs you want, etc.

 This is no simple task; it's much easier to use one of the pre-built, pre-packaged Linux distributions.

Page 24 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 2 Getting Started

MINIX is a small UNIX-like system for IBM PCs and compatibles. Little used anymore, Minix is a copyrighted product that can be downloaded in source code form for educational and research uses. In April of 1991, 21-year-old student and Minix enthusiast Linus Torvalds, in order to learn about operating systems and the Intel 386 architecture, began writing a Minix-like operating system, which he named Linux (a weak pun on "Unix" and "Linus"). He developed it using a Minix 386.

By the October of 1991, he had a working system (version 0.2) that he announced on the comp.os.minix USENET newsgroup. He released version 0.12, the stable version that began the spread of Linux, on January 5, 1992. His main interest was sharing information with fellow hobbyists, and he didn't believe it would ever be possible to port Linux to any non-386 platform. From the beginning, he provided the Linux source code to anyone at no charge under the GNU Public License (GPL).

Between 1992 and 1998, Linus and an ever-growing community of developers around the world continued enhancing and porting Linux. Version 1.0 came out in 1994, and in 1995 they succeeded in porting Linux to the Alpha and PowerPC platforms. Enhancements included such sophisticated operating system features as IPC, threading, symmetric multi-processing, a sophisticated file system, and networking.

While Linux was, and still is, freely available, building and installing it from source code is not trivial. Various groups began in the mid-1990s to package pre-built, ready-to-boot Linux distributions, usually including various pre-built utilities. Early, influential distributions included Yggdrasil's easy-to-install Plug-and-Play Linux and Slackware, geared toward Linux developers.

Linux has been ported to a remarkable number of different hardware platforms, from high-end servers and parallel clusters to a Web server host the size of a matchbox. Many new porting projects are underway all the time.

In the mid- to late-1990s, system and network administrators, frustrated with trying to run network services on NT systems, but unable to afford commercial UNIX hosts, snuck Linux PCs into their shops to run Web, file, print, DNS, firewall, and other servers. Corporations, encouraged by such open-source successes as and the Apache Web server, began to embrace low-cost, high-power Linux solutions. Distributors packaged high-quality, enterprise-ready Linux distributions, and Linux was launched.

© 2008 ITCourseware, LLC Rev 3.1.2 Page 25 Fundamentals of Linux

The Toolkit Philosophy

 Provide the user with simple utilities (sometimes called filters or tools) that do one thing well.

 Provide the user with simple ways to combine the various tools to build more powerful applications.

 Filters - take in a text stream (stdin) and produce a text stream (stdout).

 Error messages are reported on a third stream (stderr).

$ cat phonelist | grep "(303)" | sort | more

 phonelist is fed to grep, which finds all (303) and feeds them to sort, which sorts them and feeds them to more, which pages them to screen.

 Pipes - the pipe character ( | ) does "plumbing" to connect the output of one command to the input of the next.

 A series of commands connected by the pipe character is called a pipeline.

 Command Substitution - another powerful method of combining tools is to capture their output into a variable:

$ textfile_count=`ls *.txt | wc -l`

 The backticks (`) cause the output of the pipeline to be converted to a string, which is then saved in the variable textfile_count.

 Try to keep the toolkit philosophy in mind as you learn all the various Linux commands that follow. Think of how you could use them, not only by themselves, but also in combination with other commands.

Page 26 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 2 Getting Started

There are many people who use UNIX or Linux who, in my humble opinion, do not understand UNIX. UNIX is not just an operating system, it is a way of doing things, and the shell plays a key role by providing the glue that makes it work. The UNIX methodology relies heavily on reuse of a set of tools rather than on building monolithic applications.

— David Korn, Author of The Korn Shell

Perhaps the most powerful method of combining our Linux tools into powerful applications is the use of shell scripts. With scripts we can automate any combination of commands we know and also take advantage of programming language constructs like loops, conditional tests, variables, and input/ output operations and other shell capabilities.

© 2008 ITCourseware, LLC Rev 3.1.2 Page 27 Fundamentals of Linux

Linux Distributions

 Although Linux is free, building and installing it from scratch is challenging and time consuming, even for experienced engineers.

 Linux distributions package a pre-built, tested Linux operating system along with various utilities and applications.

 Most distributions are very low cost (<$100, compared to >$1000 for comparable commercial UNIX systems).

 In addition, most vendors allow you to download their distribution at no charge over the Internet.

 Just about any distribution will include all the essential software for running a network server or development workstation, plus much more stuff than you'll ever need.

 Linux, by its nature, evolves constantly.

 New Linux versions incorporate fixes and new features.

 Distibutors offer new features, software, and services with new distributions.

 Some changes, for better or worse, may break compatibility with existing applications.

 The Linux operating system itself runs with great stability, reliability, and high performance.

 Typical Linux hosts can run for months or years without rebooting.

Page 28 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 2 Getting Started

Dozens of Linux distributions have sprung up, all sharing the same Linux kernel source and differing in bundled software, packaging, installation, and support.

In 1995, Red Hat Linux began marketing its commercially-oriented distribution of Linux, bundled with hundreds of free applications and its Red Hat Package Management system (RPM). They released Red Hat Linux 4.0 for the Intel, Alpha, and Sparc platforms in 1995, and Red Hat Linux 6.0 in 1999.

The Debian project began in 1993, under the auspices of the . Its intention is to provide a packaged operating system built primarily from GNU utilities and the Linux kernel, with the work done by a distributed collection of volunteer developers and maintainers. It includes a package management system, dpkg, and a large amount of packaged software. In 1998, they released Debian GNU/Linux 2.0 for the Intel and Motorola platforms, which included over 1500 packages maintained by over 400 developers. Debian's GNU/Linux 2.1, adding support for Alpha and Sparc, came out in 1999, as did GNU/HURD, a version of Debian featuring GNU's HURD kernel instead of the Linux kernel.

Caldera Systems, founded in 1994, markets the OpenLinux commercial distribution. It uses the Red Hat Package Manager for software package installation and management. Caldera released OpenLinux 2.2 in 1999.

SuSE, founded in Germany as Gesellschaft für Software-und Systementwicklung mbH in 1992, shipped its SuSE Linux 1.0 distribution in 1992 and was the leading Linux distributor in Europe as of the late 1990s. It features RPM, the StarOffice office suite, and YaST, a graphical system administration tool. SuSE Linux 6.2 for Intel was released in 1999.

Linux is a registered trademark of Linus Torvalds.

© 2008 ITCourseware, LLC Rev 3.1.2 Page 29 Fundamentals of Linux

Free Software and Open Source Movements

 Linux provided a full operating system kernel.

 It was immediately useful, and ultimately successful, due to the vast array of utilities and libraries available from the GNU Project.

 As it grew, these also became available from other Free and Open Source projects.

 The GNU Project (for GNU is Not Unix) and the Free Software Foundation, started by Richard Stallman (the foremost guru and advocate of free software), set out in 1984 to "develop a complete Unix-like operating system which is free software."

 To legally define what "free software" meant, the FSF developed the GNU General Public License (GPL) and the term to replace the term copyright (as in "there's always a copy left!").

 When Linux was released, it filled in a missing piece for GNU, which was the yet-to-be completed kernel.

 Since the majority of the code that makes Linux usable comes from GNU, Stallman and others hold that it should be referred as "GNU/Linux."

 Numerous other projects producing free software have emerged.

 Although, with mild ideological splits between camps, some projects are billed as "Open Source" rather than "Free Software."

 For the most part, the basic intention is the same: software that is freely available to use, modify, and propagate for the good of all.

 Various entities have evolved to support Open Source and Free Software development: consortiums, foundations, nonprofit organizations, university projects, and corporate initiatives. Page 30 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 2 Getting Started

Amazing amounts of full-featured, high-quality, reliable software have come out of the Open Source and Free Software movements. Just a few …

 X Window System - X.Org Consortium, www.x.org  GNU Project - Free Software Foundation, www.gnu.org  OpenOffice - OpenOffice.org Source Project, www.openoffice.org  Gnome Office - Gnome Project, www..org/gnomeoffice  Apache - The Apache Software Foundation, www.apache.org  Mozilla - Mozilla Foundation, www.mozilla.org

From the FSF web page "The Free Software Definition" by Richard Stallman:

"Free software"' is a matter of liberty, not price. To understand the concept, you should think of "free" as in "free speech,'' not as in "free beer."

Free software is a matter of the users' freedom to run, copy, distribute, study, change and improve the software. More precisely, it refers to four kinds of freedom, for the users of the software:

 The freedom to run the program, for any purpose (freedom 0).  The freedom to study how the program works, and adapt it to your needs (freedom 1). Access to the source code is a precondition for this.  The freedom to redistribute copies so you can help your neighbor (freedom 2).  The freedom to improve the program, and release your improvements to the public, so that the whole community benefits (freedom 3). Access to the source code is a precondition for this.

From the paper "The Cathedral and The Bazaar" by Eric S. Raymond:

Linux is subversive.Who would have thought even five years ago that a world-class operating system could coalesce as if by magic out of part-time hacking by several thousand developers scattered all over the planet, connected only by the tenuous strands of the Internet?

I had been preaching the Unix gospel of small tools, rapid prototyping and evolutionary programming for years. But I also believed there was a certain critical complexity above which a more centralized, a priori approach was required. I believed that the most important software (operating systems and really large tools like Emacs) needed to be built like cathedrals, carefully crafted by individual wizards or small bands of mages working in splendid isolation, with no beta to be released before its time.

Linus Torvalds's style of development - release early and often, delegate everything you can, be open to the point of promiscuity - came as a surprise. No quiet, reverent cathedral-building here -- rather, the Linux community seemed to resemble a great babbling bazaar of differing agendas and approaches (aptly symbolized by the Linux archive sites, who'd take submissions from anyone) out of which a coherent and stable system could seemingly emerge only by a succession of miracles.

© 2008 ITCourseware, LLC Rev 3.1.2 Page 31 Fundamentals of Linux

Logging In

 To be able to use a Linux system interactively, you must first have a user account that you can log in to.

 Linux will prompt by displaying login:, and you log in by typing your user account name. Your instructor will tell you what your user name will be for this class.

login: tsmith Password: (You may not have a password, but if you do, it will not be echoed when you type it.)

$ ls ( A list of file names will appear as output of the ls command.) $

 The dollar sign is your prompt.

 The prompt you see may be different.

 Prompts are configurable by the user.

 ls is a command that you type.

 It means "LiSt the names of my files."

 The ls command has nothing to do with logging in; it is just a very common command that you can type after you log in.

Page 32 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 2 Getting Started

Each user of a particular Linux system has a unique user account name. This name is also known as a User ID. The user names on a system may follow a convention of "First initial - last name" or "Last name - first initial," or maybe even "First name - last initial." They may be employee numbers. Unless you are the System Administrator of a machine, your account name will be assigned to you by the System Administrator.

Who do you think tsmith is?

It is possible for an account to have no password. Most administrators require that all users put passwords on their accounts. We will see how to create and change a password shortly.

The prompt that Linux displays is configurable by each user. In this workbook, we will always show the prompt as a dollar sign, like this: $

© 2008 ITCourseware, LLC Rev 3.1.2 Page 33 Fundamentals of Linux

Logging Out

 To log out, type exit.

 You can also log out by pressing d.

$ exit

login:

 Now you are ready to log in again on your terminal.

Page 34 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 2 Getting Started

The exit command will always log you out.

A shell is the program that runs on your terminal (or window) when you log in. It displays the prompt and waits for your command. Thus, a shell is sometimes called a command interpreter. The word "shell" comes from the idea that the program is acting as a shell around the Linux operating system, i.e., acting as the interface between you and Linux. By the way, the innermost part of the Linux operating system is called the kernel, so the analogy is that we have a shell around a kernel.

There are several shell programs available on Linux, and some provide additional ways to log out. The C shell (csh) lets you type exit or logout. All shells will let you log out with d, but they may have an option set that ignores d so that you don't inadvertently log out by accidentally pressing d.

We will study shells in much more detail later in the course. For now, just use exit to log out, and be aware that there are other ways. (Of course, you might want to try logout and d. Please experiment in this class!)

© 2008 ITCourseware, LLC Rev 3.1.2 Page 35 Fundamentals of Linux

Try a Few More Commands

 After logging in, try each of these commands, just to get some hands-on practice.

 Remember, the dollar sign ($) represents the Linux shell prompt. Don't type the dollar sign!

$ who Shows who is currently logged on (May not work properly on an X-terminal)

$ who am i Shows who you are

$ date Shows the date and time

$ cal Shows calendar of the current month

$ cas A non-existent command we use to demonstrate an error message

Page 36 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 2 Getting Started

© 2008 ITCourseware, LLC Rev 3.1.2 Page 37 Fundamentals of Linux

Changing Your Password

 You can create a password if you don't have one, or change an existing one, with the passwd command.

 In the following example, the user tsmith selects the password fl0wer?:

$ passwd Changing password for tsmith (current) UNIX password: tsmith's password New UNIX password: fl0wer? Not echoed Retype new UNIX password: fl0wer? Not echoed

 The new password must be used at the next login.

Page 38 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 2 Getting Started

There are rules that apply to passwords. To read them, type:

$ man passwd

This will display the manual entry for the passwd command.

The next page describes how to use the on-line Linux reference manuals.

If you forget your password, it must be reset by the System Administrator. Not even the SA can find out what your password is.

© 2008 ITCourseware, LLC Rev 3.1.2 Page 39 Fundamentals of Linux

Online Documentation - man Pages

 Most Linux systems keep electronic copies of the Linux reference manuals in files on disk. They are accessible with the man command (man is short for manual).

 To read the manual entry for a particular command, for example passwd, type:

$ man passwd

 The entry for the passwd command will be displayed on your terminal, pausing when a full page has been displayed.

 Press the key for the next line, the bar to display the next page.

 To quit without displaying the rest of the manual entry, use the q (for quit) key.

 Sometimes you see the names of commands written in the form command(N) where N is a number. For example:

passwd (1) - change user password passwd (5) - password file

 This means that there is documentation for passwd in both Sections 1 and 5 of the Linux reference manuals (specified by including it in the man command).

$ man 5 passwd

Page 40 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 2 Getting Started

Descriptions of commands in the on-line documentation are known for their terseness. It has been said that there are three rules to be aware of when reading Linux manual entries:

Rule 1. Every word counts. Rule 2. They only say it once. Rule 3. You must know a fair amount of terminology before reading most entries.

We recommend that during your Linux learning curve you have a more tutorially-oriented book available, such as those listed under Suggested References and Reading in Chapter 1 of this workbook. Over time, the on-line manuals can become a more efficient way for you to look things up.

On another note, the man command works fine if you know the name of the command that you want to read about. But what if you want to change your password and you don't know the name of the command to use? Well, the man command has a useful option, -k, which will display the titles of all commands that contain the specified keyword. For example:

$ man -k password chpasswd (8) - update password file in batch dpasswd (8) - change dialup password gpasswd (1) - administer the /etc/group file htpasswd (1) - Create and update user authentication files mkpasswd (8) - Update passwd and group database files passwd (1) - change user password passwd (5) - password file

After perusing the titles of the commands, you can pick the one that you need.

The Linux manual is divided into topical sections as follows:

Section 1 Commands Section 5 File Formats Section 2 System Calls Section 6 Games Section 3 Library Functions Section 7 Miscellany Section 4 Special Files Section 8 System Administration Commands

© 2008 ITCourseware, LLC Rev 3.1.2 Page 41 Fundamentals of Linux

Online Documentation - info Pages

 A large portion of the commands used in Linux were developed or influenced by the GNU Project of the Free Software Foundation.

 The preferred method for GNU Project documentation is the Texinfo file.

 A Texinfo file is structured like a book, with chapters, sections, sub- sections, (and even sub-sub-sections), each making up a node of the documentation.

 A single Texinfo file can be processed by different programs to produce its documentation in a variety of forms, including man pages, Info files, HTML, and print.

 The info command (with a user interface based on Emacs) provides a character- based hypertext system to browse the nodes of an Info file.

 info can be run with no arguments to access the top level node of the documentation (also called the directory node), or with the name of a topic or command to access specific information.

$ info Access the top level of the documentation $ info passwd Get information on the passwd command $ info regex Get information on the regular expression library

 A given node can connect to others with hyperlinks or cross-references.

 A cross-reference shows as a line beginning with an asterisk.

* Invoking GCC:: Command options supported by `gcc'

 To visit a cross-reference, merely move the cursor anywhere on that line and press .

Page 42 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 2 Getting Started

There are limitless ways of navigating documentation in info. Almost anything you know from Emacs will work. For the full story, use the info command on itself: info info. In lieu of that, here are some addition useful navigation commands:

Move to the next cross reference Page down Page up L Redraw the screen

B Beginning of node D Move to Directory node E End of node I Search node Index for text L Move to Last node visited (like back on a web browser) M Select a Menu item by name N Next node P Previous node Q Quit S Search node for text T Move to Top level node U Up from this node

In addition to the man pages and Info files, Linux systems will often have a wide variety of information available in the directories /usr/doc or /usr/share/doc. Here you can find quick reference Frequently Asked Questions files in the FAQ subdirectory; longer, tutorial "how to" files in the HOWTO subdirectory; and documentation for many of the installed software packages in the various other subdirectories.

If this documentation was omitted when Linux was installed on your machine, you can find most of the same information (and often more up-to-date) on the web. A great starting place is the Linux Documentation Project at www.tldp.org.

© 2008 ITCourseware, LLC Rev 3.1.2 Page 43 Fundamentals of Linux

Labs

‚ Study the manual entry for the cal command. On what day of the week were you born?

ƒ Execute the who command with the command-line option that puts a header on the output. Options on Linux commands are preceded by a hyphen.

$ ls -l $ man -k who

„ Use the wc command to print the number of bytes, words, and lines in the file memo.

Read about some of the options to wc in its manual entry. Use wc to print just the number of lines in memo and bigfile.

Page 44 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 2 Getting Started

Questions you need answers to in order to be successful on your system when you get back to work:

1. What is my login name?

2. What is my password?

3. Which key backspaces?

4. How do I interrupt a command? (Usually c)

© 2008 ITCourseware, LLC Rev 3.1.2 Page 45 Chapter 6 Editing With vi

Chapter 6 - Editing With vi

Objectives

 Use basic vi commands to create and modify files.

 Explain the difference between the input and command modes of vi.

 Move the cursor anywhere within the text.

 Delete a character on the line.

 Delete a line.

 Create a new line within already existing lines of text.

 Undo the last change or all changes to a line.

 Save intermediary changes to files.

 Abort all changes made to a file.

© 2008 ITCourseware, LLC Rev 3.1.2 Page 97 Fundamentals of Linux

What is vi?

 vi is the standard text editor for UNIX systems.

 It is used to create new text files and to modify existing ones.

 vi is powerful, and once mastered, will significantly increase your text editing productivity.

 Even if you plan to use some other editor on your system, it is good to know how to use vi, since it will be on every UNIX system you will encounter, even if your normal editor is not available.

 The Linux version of vi is named (for vi improved).

 vim works just like traditional UNIX's vi, but has many added features.

 The material in this chapter works in both vim and vi.

Page 98 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 6 Editing With vi

vi and ex

One of the earliest text editors for UNIX was a line editor called ed. Teletypewriters were the predominant terminal used at that time (early 1970s), and ed was designed for use with them. It was a very efficient editor for its time and was used for several years.

In the late 1970s, UCB UNIX guru Bill Joy produced, among other programs, a new text editor called ex. The ex editor provided enhanced file navigation and pattern-handling capabilities over ed. In addition, for users with access to CRT terminals, a full-screen visual mode was provided. The ex editor can switch between line and visual modes (vi at the ex prompt to get visual mode, Q in visual mode to get back to line mode). Since users much preferred the visual mode, the vi command was created. vi and ex are actually the same program, except that when invoked as vi, it starts in visual mode, rather than line mode. vi is compact, efficient, extensible, and convenient for editing multiple files, both large and small. It is universally available on UNIX and works consistently on a wide variety of terminals (UNIX supports hundreds). It permits customization and interoperates very well with all other UNIX text-manipulation commands. Once mastered, vi editing is very fast, since vi makes efficient use of the keyboard.

Though some have found it difficult to learn, vi remains very popular among UNIX users and programmers; its popularity is rivaled only by the public-domain editor emacs.

The vi editor can handle very large files, but there are limits to what it can do. Typical limits for most implementations of vi include:

 1024 characters per line  250000 lines per file

Linux's vim has much higher limits (e.g., 2 billion characters per line, 2 billion lines per file). However, additional limits, such as maximum file size or maximum memory per user process, may be imposed by the system. If you need to edit files that are larger than this, you will need to break the file into smaller pieces or use another editing tool (such as sed, the streaming editor).

© 2008 ITCourseware, LLC Rev 3.1.2 Page 99 Fundamentals of Linux

Getting Started - vi Buffering

 You can start vi with no arguments, or with the name of a new or existing file:

$ vi $ vi memo $ vi people

 Note that there is no prompt in vi - editing takes place at the cursor.

 Like most editors, vi does not edit your file directly, but works with a copy of it in its buffer.

 The original file will not be updated unless the vi buffer is explicitly saved.

$ vi file file The vi buffer

Original Copy of Enter file file vi on disk cmds

Changed Yes Save Modified file file? buffer New No version on disk Abort edit session, throw away buffer, leave disk file unchanged

Page 100 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 6 Editing With vi

vi Buffering

The vi buffering process has advantages and disadvantages for users.

One advantage is that any changes made to a (possibly) valuable data file are not made to the actual file until the user explicitly saves them. If, after editing, you decide that the original file should not be modified, you can choose not to.

One drawback can occur if several users edit the same file at the same time. Since they are all working on their own buffered copies of the file, as each one saves their version, it will overwrite the previous version of the file. This means that in the case of several people editing the same file simultaneously, the last one to save the file wins!

Buffer Recovery

The vi editor stores temporary copies of the file it is editing in the /tmp directory (although some vendors use other locations). One reason for the temporary copy is that in case of a system crash or other unintentional stoppage of a vi session, the edit session can be recovered.

Recovery is done with the -r option to vi. After a system crash, when you log back on, you will have an email message from vi telling you how to recover your session. You will need to start vi as:

$ vi -r filename

You will then be back in the file you were editing when the system went down, with most of the changes you had made intact.

© 2008 ITCourseware, LLC Rev 3.1.2 Page 101 Fundamentals of Linux

Command Mode and Insert Mode

 In vi you are always in one of two modes:

 Command mode - where each character you type is taken as a command to vi to do something like move the cursor, delete a character, scroll the screen, or cut and paste.

 Insert mode - where each character you type is inserted into the buffer.

 vi always begins running in command mode.

 It enters insert mode in response to one of six possible commands.

Page 102 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 6 Editing With vi

Why Two Modes?

When you are editing a file, there are two basic operations you need to perform:

1. Move around in the existing file (move the cursor, delete text, etc.).

2. Type in new text.

Some systems have special keys (Arrow keys,, , , , etc.) or graphical objects (scrollbars, etc.) for cursor motion. vi was created with portability and terminal independence in mind. Since many terminals (such as the industry-standard VT100) lack such special features, the standard typewriter keys must do double duty. For this to work, vi has two modes:

Command Mode - each key performs a specific vi command.

Insert Mode - each key inserts a character into the file. vi begins in command mode. Becoming a proficient vi user involves learning the many flexible ways of getting from command mode to insert mode.

Once in insert mode, the key returns vi to command mode. On a terminal with no key, [ is equivalent.

The Colon Commands

While in command mode, the full ex command set is available. Since these involve multiple keystrokes, you must first type a : to place the cursor at the bottom of the screen and prepare vi for such a command.

Finally, if your cursor appears at the bottom of the screen, and you can't get off it, you are in ex, the line-editor. To return to visual mode, type vi at the colon prompt.

GOTCHA:

The ex line-editor is toggled by hitting a Q in command mode in vi. This is easy to do inadvertently while typing :q to exit vi.

© 2008 ITCourseware, LLC Rev 3.1.2 Page 103 Fundamentals of Linux

Getting Started

Syntax:

$ vi newfile

. . . or

$ vi existing_file

Example:

$ vi memo

(The contents of file memo fill the screen.)

 Note that there is no prompt in vi; editing takes place at the cursor.

Page 104 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 6 Editing With vi

If you invoke vi without a file name, you will get a screen just like when you create a new file. vi will work just fine on this unnamed file, but when you need to save the file, you will need to give it a name under which to be saved. (We will see how to do this shortly.)

A problem that can arise with vi if you are using an X-terminal, is a function of the X-windowing environment. vi was designed to work with fixed-format terminals, 80 characters per line, 25 lines per screen. Because you can enlarge or shrink the terminal window on an X-terminal using a mouse, the number of lines and columns in the window is variable. If you change the size of the window, vi still thinks it is talking to an 80 by 25 terminal, and several parts of vi will not function properly.

To deal with this, there is a utility called resize that you can run in a nonstandard-sized window. resize will calculate the number of rows and columns of text that will fit into the window and make this information available to vi and any other programs that need to know. After changing the size of the window containing the terminal (xterm, hpterm, etc.) type the following command:

$ eval 'resize'

Now vi and other like programs will function properly. Each time you change the size of the window, you need to run the command again.

Some vendors have modified their X environments so that the environment is updated automatically when a window is resized, thus eliminating the need to run resize.

© 2008 ITCourseware, LLC Rev 3.1.2 Page 105 Fundamentals of Linux

Moving the Cursor Around

 There are several ways to position the cursor on the screen while in command mode. We suggest the following be used:

 h key means move left  j key means move down  k key means move up  l key means move right

 In addition, these keys will also work:

 bar means move right  means move left  means move down  Arrow cursor keys

Page 106 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 6 Editing With vi

Why h, j, k, and l?

It may seem like these are just arbitrary keys that were chosen for moving the cursor. l might make sense for left, but it actually moves right!

There is reasoning behind these choices. If you look carefully at what and where these keys are on a "qwerty" keyboard, you will see that the h, j, k, and l keys are the right-hand home-row keys for touch- typing.

H J K L

If you study which cursor movements are most often used in editing, you find that moving down is used most often, followed in order by up, right, and left. j was chosen because it is the home-row index finger, which is generally your strongest finger. Next is k, your middle finger, followed by l, your ring finger. Finally, h (left, the least used motion) is your index finger moved inward one key. For touch typists (and to be really proficient in vi you should be a touch typist) this makes moving around the screen very fast and quite natural. Not having to pick your hand up to reach the cursor keys or grab the mouse speeds up editing significantly.

© 2008 ITCourseware, LLC Rev 3.1.2 Page 107 Fundamentals of Linux

Inserting Text

 In command mode, type:

i — Insert to left of cursor.

a — Append to right of cursor.

 i and a both put you in insert mode. Type text (including new lines) until you are done inserting, then press to go back to command mode.

 There are also upper case versions of i and a:

I — Insert at beginning of line.

A — Append at end of line.

Page 108 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 6 Editing With vi

Why do we need both i and a?

Suppose you need to add text to the end of a line. In vi, use l to move to the end of a line. Now try to use i to put new text to the right of the cursor. You can't do it! There needs to be a command to explicitly move the cursor over one more character to the right, allowing the new text to go in the proper place.

Why won't vi let you move off the end of the line?

To look at this, we first have to understand the nature of text files. A text file is made up of ASCII characters in sequence, stored in a file. The following three lines are representative of what you would see in vi when editing a file:

The quick brown fox jumped over the lazy dog 0123456789

Inside the file itself, the following data is stored:

The quick brown fox(NL)jumped over the lazy dog(NL)0123456789 where (NL) is a newline character (Line-Feed, ASCII 10, or CTRL-J). The whitespace that you see in vi following each line is not real. It is an artifact of the way the terminal treats receipt of a newline character, which is to move the cursor all the way to the left and down one line. vi can only position the cursor where a character truly exists. Since there are no real spaces to the right of the lines, you can't move the cursor there.

If you get confused about which mode you are in, there are some things you can do to help yourself:

Hit the key: If you are in insert mode, it will switch you to command mode. If you are in command mode, it will just beep at you.

Type the following: :set showmode

This will enable a prompt at the bottom of the screen. We will investigate the :set command in the next chapter.

Stay in command mode most of the time. Move around the screen until you need to insert text. Go into insert mode and type in the new characters. Then immediately hit the key to go back to command mode. If you get used to doing this, you will be in command mode most of the time while you are editing, and you will have fewer j's and k's inadvertantly inserted into your text.

© 2008 ITCourseware, LLC Rev 3.1.2 Page 109 Fundamentals of Linux

Deleting a Character or Line

 In command mode, type:

x — Delete the character at the cursor.

dd — Delete the line the cursor is on.

 With both of these commands, you stay in command mode.

Page 110 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 6 Editing With vi

The x and dd commands can both be repeated by prepending a number in front of the command.

The command dd will delete the current line. If you type the command 5dd , it will delete the current line and the next 4 after it, for a total of 5 lines deleted. Likewise, 12x will delete 12 characters. Note that if there are less than 12 characters on the line starting from the current cursor position, the deletion will not carry over to the next line: vi makes a very definite separation between acting on characters on a line and acting on multiple lines.

You will also find repeat specifier numbers work with most vi commands. Try it with h, j, k, and l.

© 2008 ITCourseware, LLC Rev 3.1.2 Page 111 Fundamentals of Linux

Undo Last Command

 In command mode, type:

u — Undo most recent command. Successive u commands will continue to undo commands in reverse order.

U — Undo all changes to current line. You cannot have left the current line (moved the cursor from it).

Page 112 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 6 Editing With vi

The undo commands are very useful in vi, in that they allow you to try things you might otherwise not with the knowledge you can undo whatever changes result.

There is a big difference between Linux's vim undo command and the traditional vi undo command. In traditional vi, the u command will only undo the most recent change. If you make a change that is incorrect, and then make another without undoing the first one, it's too late. Successive u commands will toggle, because a second undo will undo the undo! In vim, the u command continues undoing previous commands, eventually taking you back to the beginning of your vim session!

The U command is interesting in that it is designed specifically to work on multiple changes to a single line. Each time you move the cursor to a new line, vi takes a snapshot of the characters on that line and stores them in a special line buffer. If, at a later time (say, after making several changes on the line), you use the U command, vi gets the contents of the line buffer and replaces them on that line. This has the effect of undoing one or many changes on a given line. But remember, if you move the cursor to a new line, vi will immediately copy THAT line to the line buffer, and the original copy of the previous line is lost.

Investigate:

Why can you use the u command to undo the deletion of a line, but not the U command?

© 2008 ITCourseware, LLC Rev 3.1.2 Page 113 Fundamentals of Linux

Opening a New Line

 In command mode, type:

o — Insert a new line below current line, move cursor there, and be in insert mode.

O — Insert a new line above current line, move cursor there, and be in insert mode.

 o and O have the same effect as i and a, but they put the cursor on a new line as they enter insert mode.

Page 114 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 6 Editing With vi

© 2008 ITCourseware, LLC Rev 3.1.2 Page 115 Fundamentals of Linux

Save Your Work or Abort the Session

 In command mode, type:

:wq — Write the buffer back to the file, then quit vi.

:q! — Quit vi without saving any changes. The original file is left unchanged.

ZZ — Write the buffer back to the file (zz).

Page 116 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 6 Editing With vi

The colon commands are actual ex editor commands. These commands can be used any time in vi by typing a : in command mode. The : prompt will then appear in the bottom left corner of the screen.

The w command in ex writes the file. If you invoke :w by itself, vi will write the file under the same name that you used when you invoked vi. You can also specify a file name with the write command, as in :w filex, and the current edit session will then be written to the (possibly new) file filex. The original version of the file will be left unchanged.

The :q command quits vi. :wq says "write the file, then quit vi."

If you try to quit vi with :q, and you have made changes during the edit session and have not yet saved your work with :w, then vi will refuse to quit the session and will send you an error message. You can force vi to quit by adding an ! to the :q command (the ! is used in several situations in vi to force commands, as we will see).

ZZ is a true vi command: it does not invoke the ex command line, and immediately does a write and quit.

A note of warning about ZZ:

ZZ works just fine: it saves your work, then terminates vi. However, if instead of typing ZZ you type Z(z), something completely different happens. Z is used for job control in UNIX: it suspends the current program and puts it in the background. If you type Z from inside vi, it will look like ZZ to you, in that you will get a UNIX prompt back and can then continue working at the command line. But the file you were working on has not been saved and the vi session is still running in the system, waiting for you to reactivate it!

A way to avoid this is to get used to using the :wq and :q! commands (we will see several more : commands in the next chapter).

© 2008 ITCourseware, LLC Rev 3.1.2 Page 117 Fundamentals of Linux

Review of vi Commands

Return to command mode

h, Move cursor left j, Move cursor down k Move cursor up l, Move cursor right

i Insert left of cursor a Insert right of cursor I Insert at beginning of line A Append at end of line

x Delete one character dd Delete line

o Open (insert) below current line O Open (insert) above current line

u Undo most recent change U Undo changes to current line

:wq, ZZ Write buffer and quit :q! Quit without saving changes

Page 118 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 6 Editing With vi

© 2008 ITCourseware, LLC Rev 3.1.2 Page 119 Fundamentals of Linux

Labs

‚ Edit the file filec by typing vi filec. Note the position of the cursor. Move the cursor to the end of the line and then back to the beginning. Do the cursor motion three different ways.

ƒ Edit memo. Delete the third line. Type :q!. Back at your shell prompt now, type more memo. Is the third line gone? Why not? Repeat the exercise, but this time exit vi such that the file memo is changed on disk.

„ Copy memo.copy to memo. This will restore the original memo file after the edit in Step ƒ. Edit memo and position the cursor on a line in the middle of a paragraph. Delete two characters on the line with xx, then press u for undo. Press u again. What happened? What about pressing u once more? Try this exercise with dd now. Delete several lines, then bring them back one at a time with repeated undo commands.

Experiment with r after undoing a command. The r means "redo."

Delete the first word on a line. Then move the cursor several words to the right and insert a word. Remember to press to leave insert mode. Now type capital U. What happened? Repeat the exercise, but after inserting the new word and pressing , move the cursor off the line (up or down) then back to the line. Now press U. What happened?

† Practice inserting text with i, a, o, and O. Remember to press to leave insert mode and return to command mode each time.

‡ Repeat the above with I and A.

ˆ The movement and delete commands can be preceded by an integer count that will cause the command to be executed n times. For example, 5j will move the cursor down 5 lines; 2x is equivalent to xx; 6dd will delete 6 lines.

Experiment with the count specifier. Remember to use the undo command to facilitate your practice, otherwise you may quickly end up with no file left!

Page 120 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 6 Editing With vi

© 2008 ITCourseware, LLC Rev 3.1.2 Page 121 Chapter 21 X Windows and Desktops

Chapter 21 - X Windows and Desktops

Objectives

 Describe the origin and operation of the X Window System.

 Execute a GUI-based program on a remote display.

 Explain the origins and compare the features of the Gnome and KDE.

 Find Open Source alternatives to common applications.

© 2008 ITCourseware, LLC Rev 3.1.2 Page 365 Fundamentals of Linux

The X Window System

 Found at www.x.org, it is officially called "X" or "X Window System," although it is commonly, albeit incorrectly, referred to as "X Windows."

 An X server manages the Graphical User Interface (GUI) for one or more displays on a Linux machine, as well as handling events from the user (mouse movements, key presses, button clicks, etc.) and providing routines to draw various items on the display (characters, lines, arcs, bitmaps, etc.).

 An X client is an application that wishes to display graphical information.

 A client will attach to a particular display on a particular server and request that the server create one or more windows on its behalf.

 Any events that occur while the client's windows have focus will be sent to the client for processing.

 In response, the client can send back graphics directives to update the display.

 The protocol used to encode these events and display directives between client and server is also called X.

 Often, the client and server processes will be running on the same machine, in which case they communicate through a UNIX socket.

 It is possible (and useful!), however, for the client and server to reside on separate machines, communicating through an Internet socket using the TCP/IP network protocols.

 Xfree86 is the version used in Linux, built on the latest release from the X consortium: X11 (www.xfree86.org).

Page 366 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 21 X Windows and Desktops

X Window System started with xinit: the X server and a single xterm window running

Running xeyes from within the xterm window.

xinit - start X and a single terminal window from the terminal window, so that you can run other X applications. This is the minimal useful configuration, with no menus, widgets, or icons.

startx - start X and a window manager or desktop, depending on the configuration.

© 2008 ITCourseware, LLC Rev 3.1.2 Page 367 Fundamentals of Linux

Using X

 An X client must specify the display name of the X server it wants to access.

 Display names have form: hostname:displaynumber.screennumber.

 The display name is typically set in the DISPLAY environment variable, however, most X clients also support the -display option.

$ export DISPLAY="rocketskates.acme.org:0.0" or $ xclock -display "192.168.14.3:0"

 Most X clients also support the -geometry option to specify basic layout information.

 Geometry information has form: xsize x ysize + xoffset + yoffset.

$ xeyes -geometry 100x100+50+120 100 by 100 offset to (50,120) $ xclock -geometry +20+75 Default size offset to (20,75)

 An X client can only attach to a server if it is authorized to do so.

 X servers provide several mechanisms to authorize client access.

 The simplest is Host Access, which uses the xhost command on the server to specify which client machines are allowed access.

$ xhost +192.168.14.3 Allow access from this IP $ xhost +pogostick.acme.org Allow access from this DNS name $ xhost + Allow access from everyone $ xhost Show status of access control

Page 368 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 21 X Windows and Desktops

hostname The DNS name or IP address of the X server. If the hostname is omitted the server is assumed to be local. displaynumber A display is a keyboard and pointer device associated with one or more monitors. display numbers start at 0 and most workstations will only have one display. screennumber Some video cards can support multiple monitors with each monitor assigned a screennumber starting at 0. If the screennumber is omitted, 0 is assumed.

In addition to -display and -geometry, here are some other common options that most X clients support:

-bg color-background color Specify the background color of the client window -fg color-foreground color Specify the foreground color of the client window -bd color-bordercolor color Specify the border color of the client window -title titlestring Set the window title to titlestring -iconic Start the client in iconized (minimized) form

Colors can be specified as red/green/blue values with the syntax rgb:red/green/blue where red, green, and blue are hexadecimal values. Alternatively, colors can be specified by name. Color names are defined in the file rgb.txt, which is typically located in the directory /usr/X11R6/lib/X11/rgb.txt.

rgb:fff/0/fff Magenta rgb:7ff/7ff/7ff Gray50 (50% gray) rgb:0/0/0 Black rgb:64/95/ed Cornflower blue

© 2008 ITCourseware, LLC Rev 3.1.2 Page 369 Fundamentals of Linux

Window Managers and Desktops

 Window managers provide frames and widgets for the individual windows used to display applications running on X.

 They provide a basic, unified look and feel for window titles, borders, and menus, as well as handle basic functions, like window resizing, maximizing, iconifying, and closing.

 Various window managers have been developed as X has evolved. Some of the early ones are still used, but they are not all desktop aware.

 twm — Tab/Tom Window Manager - early yet very influential.  mwm — Motif Window Manager - standard for the Motif library.  fvwm — Fabulous/Fast/Funny … Virtual Window Manager - works like twm, look likes mwm, implemented virtual display and themes.

 Desktops extend this unified look and feel beyond individual windows and provide common ways for applications to interact with each other and the system.

 They provide cross-application functions, like copy/cut/paste, drag and drop, and clipboards, and also support configurable menu bars, shortcuts, scripting, and themes.

 The two most popular desktops in use with Linux are Gnome and KDE, both of which are endlessly customizable with configuration parameters and modules.

 Various window managers have evolved that work with these desktops:

 — the default window manager for Gnome.  sawfish — another popular Gnome-aware window manager.  kwin — the default window manager for KDE.

Page 370 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 21 X Windows and Desktops

Running mwm from within an xterm window - the Motif look and feel.

Running twm instead for a different look and feel.

© 2008 ITCourseware, LLC Rev 3.1.2 Page 371 Fundamentals of Linux

The Gnome Desktop

 Gnome originated in 1997, in part as a response to concerns about the use of the Qt toolkit in KDE, which, at the time, did not meet the criteria for free software.

 The Gnome desktop provides a consistent operating environment based on well-researched and documented human interface design principles.

 It is host to a wide variety of user applications.

 Office applications include:

 Abiword — a full-featured, cross-platform word processor.  — a full-featured, cross-platform .  Gnome PIM — Personal Information Manager.

 Graphics applications:

 The GIMP — Photoshop substitute.  gpaint — Microsoft Paint substitute.  Eye of Gnome — image and photo collection viewer and manager.

 Editing applications:

 — HTML Editor.  — text and code editor.

 System applications include:

 COG — COnfigurator for Gnome.  Gnome Terminal — terminal emulator.  Quark — audio player.

 Gnome, written primarily in C, is based on the GTK+ widget toolkit, which was originally created for the GIMP project.

Page 372 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 21 X Windows and Desktops

The official website (www.gnome.org) describes Gnome as:

GNOME is Free Software and part of the GNU project, dedicated to giving users and developers the ultimate level of control over their desktops, their software, and their data.

The Gnome Desktop with and gnome-terminal running.

© 2008 ITCourseware, LLC Rev 3.1.2 Page 373 Fundamentals of Linux

The KDE Desktop

 Originated in 1996 as the Kool Desktop Environment, it has grown to a full-featured, highly integrated desktop.

 The latest version has 4 million lines of code contributed by over 800 developers worldwide.

 Konqueror — Web Browser / File Manager

 KOffice — Integrated Office Suite

 KWord — word processor.  KSpread — spreadsheet.  KPresenter — presentation tool.  Kivio — diagramming tool.  Krita — photo editing.

 KDE PIM — Personal Information Manager

 KMail — email client.  KAddressBook — address book.  KOrganizer — calendar and scheduling.  Knotes — reminders.  Kpilot — PDA manager.

 KDE Admin — System Administration Tools

 Kdat — Tape Backup.  KsysV — process management.  Kpackage — software installation.

 KDE follows an object-oriented philosophy throughout and is written in C++.

 KDE applications are closely integrated and can be scripted using the Desktop COmmunications Protocol (DCOP). Page 374 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 21 X Windows and Desktops

From the KDE Website (www.kde.org):

KDE is a network transparent contemporary desktop environment for UNIX workstations. KDE seeks to fill the need for an easy to use desktop for UNIX workstations, similar to the desktop environments found under the MacOS or .

The KDE Desktop with kmines and konsole running.

KDE uses an open source version of Qt, a multi-platform GUI toolkit. Qt, in turn, implements a rich set of GUI objects on top of the X Windowing System. Many applications use Qt, but other applications (particularly KOffice) use a set of higher-level objects called KParts. Qt and KParts allow developers to quickly create applications that share a common user interface and seamlessly interoperate with the KDE desktop and existing applications.

KesnoitacilppAED ciffOK snoitacilppAEDK strapK

TQ/seirarbiLEDK

11X

XINU

© 2008 ITCourseware, LLC Rev 3.1.2 Page 375 Fundamentals of Linux

Applications: The GIMP

 The GNU Image Manipulation Program (GIMP) is a free software replacement for programs such as Adobe's Photoshop and JASC Software's Paint Shop Pro.

 GIMP can be found at www.gimp.org.

 GIMP boasts a comprehensive set of professional-level features:

 Full suite of painting tools: Brush, Pencil, Airbrush, Eraser, Clone, etc.  Support for multiple layers and channels (including alpha channel).  Advanced scripting capabilities with Script-fu.  Multiple Undo/Redo levels (limited only by disk space).  Load and save animations in a convenient frame-as-layer format.  Transformation tools including rotate, scale, shear and flip.  Load, display, convert, save to many file formats including .gif, .jpg, .png, .xpm, .tiff, .tga, .mpeg, .ps, .pdf, .pcx, bmp, and many others.  Selection tools, including rectangle, ellipse, free, fuzzy, bezier and intelligent.  Open plug-in architecture allows easy addition of new file formats and new effect filters.  Over 100 plug-ins already available and more constantly in the works.

 GIMP can also be used non-interactively for batch mode image production and format conversion.

Page 376 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 21 X Windows and Desktops

The GIMP running on Tux the Linux Penguin

© 2008 ITCourseware, LLC Rev 3.1.2 Page 377 Fundamentals of Linux

Applications: OpenOffice

 Free software replacement for the extremely popular Microsoft Office Suite.

 Formerly StarOffice from Sun.

 Writer — a word processor that can read and write Microsoft Word files.

 Calc — a spreadsheet that can read and write files.

 Impress — a presentation creator that can read and write Powerpoint slides.

Page 378 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 21 X Windows and Desktops

OpenOffice programs writer and calc running on the Gnome desktop.

© 2008 ITCourseware, LLC Rev 3.1.2 Page 379 Fundamentals of Linux

Applications: Web Browsers

 There are several cutting-edge web browsers available for Linux that include features like tabbed windows, split screens, mouse gestures, and keyboard shortcuts.

 Mozilla

 Open source, originally built from the Netscape Communicator 5.0 source code released in 1998.  Next-generation code base is currently in development as Firebird  www.mozilla.org.

 Opera

 "The fastest browser on earth."  Small memory footprint, fast to load.  Runs on a wide variety of platforms, including handhelds and cellphones.  www.opera.com

 Konqueror

 Standard and highly integrated in KDE where it serves as file manager, web browser, and document viewer front-end.  Handles content display with a variety of viewer components embedded via the KParts library. Examples: KWrite — text files. KView — image files. KGhostview — PostScript files. KWord, KSpread, KPresenter — various office type files.  konqueror.kde.org

 These are the most popular web browsers currently available, but many others exist.

Page 380 Rev 3.1.2 © 2008 ITCourseware, LLC Chapter 21 X Windows and Desktops

Konqueror running with tabs on multiple Linux related websites.

© 2008 ITCourseware, LLC Rev 3.1.2 Page 381