UNIX For Beginners Second Edition

Transcription

UNIX For Beginners — Second EditionBrian W. KernighanModified for Williams byT. Murtagh and B. MooreAdditional Modifications for Clemson byD. HouseFebruary 7, 2011Introductiona unix terminal running on your machine. Performing the “experiments” described in the document asyou read it will increase your understanding.The UNIX operating system is easy to use, andpresents few of the usual impediments to getting thejob done. It is hard, however, for the beginner toknow where to start, and how to make the best useof the facilities available. The purpose of this document is to help new users get used to the main ideasof the UNIX system and start making effective useof it quickly. It is intended as an introduction to thesystem rather than as a reference manual. Where appropriate, the reader is directed to other documentsdescribing various details of the system.This document has four sections:11.1Getting StartedLogging InYou must have a UNIX login name. At Clemson,this will be your standard Clemson userid and yourpassword. If you are on your own system, it will bethe userid and password that you created for yourselfwhen you built the system.Normally, UNIX should type1. Getting Started: How to log in, how to type,what to do about mistakes in typing, how to logout.login:When you get a login: message, type your userid.2. Manipulating Files: A brief introduction to the Follow it by a RETURN; the system will not do anythingfile system and the commands used to create and until you type a RETURN. If a password is required,you will be asked for it, and printing will be turnedmanipulate files.off while you type it. Don’t forget RETURN.3. More About Files: Directories: Discusses the directory structure used to access files.1.2Typing Commands4. The Shell: Introduces some helpful features ofWhenever you type something, it goes to the windowthe UNIX command interpreter.the mouse is currently in. System commands are acThis document assumes that you are reading it cepted by the “xterm” window on your screen. Sowhile sitting in front of a unix workstation, and have before typing any of the commands discussed below,1

you must make sure that the mouse is in the “xterm”window on your screen.One you have moved the mouse into your “xterm”,try typingrecover. The backspace key erases the last charactertyped. Successive uses of backspace remove characters back to the beginning of the line (but not beyond). So if you type badly, you can back up asmuch as you need.dateIf you have made such a major typing mistake thatitwould be easiest to discard the current line andfollowed by RETURN. You should get back somethingstartover, you can do this by typing Control-c.likeMon Jan3 14:17:10 EST 19911.4Don’t forget the RETURN after the command, or nothing will happen. If you think you’re being ignored,type a RETURN ; something should happen. RETURNwon’t be mentioned again, but don’t forget it — ithas to be there at the end of each line.Another command you might try is finger, whichdisplays information about users of the system.Stopping a ProgramThe control-c character has another importantfunction. You can stop most programs by typingcontrol-c. In a few programs, like the mail program,control-c stops whatever the program is doing butleaves you in that program.If you wish to stop a program temporarily so thatyou can perform some other task and then restart thestopped program later, type control-z. The jobscommand will display a list of all jobs that have beensuspended in this way. The command fg can be usedto restart suspended jobs. Simply typingfinger some-user’s-namegives something likeLogin name: lenhartIn real life: Bill LenhartDirectory: /home/bullseye/lenhartShell: /bin/cshLast login Fri Sep 23 17:29 on ttyp0 from 192.31.45.228New mail received Mon Jan 2 16:09:19 1989;unread since Mon Jan 2 16:09:24 1989No Plan.fgwill restart the most recently suspended job. Alternately, a job number may be included as an argumentIn general, finger some-user’s-last-name will display in the fg command to request that a particular susinformation about that user, including the user’s lo- pended command be restarted (each job’s number isdisplayed in square brackets by the jobs command).gin name.If you just want a command’s output to pause, forIf you make a mistake typing a command name,exampleto keep something critical from disappearand refer to a non-existent command, you will beingoffthescreen, type control-s. The output willtold. For example, if you typestop almost immediately. When you want to let yourfngerprogram’s output continue, type control-q.you will be told1.5fnger: not foundUNIX has full read-ahead, which means that you cantype as fast as you want, whenever you want (exceptduring login), even when some command is typing atyou. If you type during output, your input charactersmay appear intermixed with the output characters,but they will be stored away and interpreted in thecorrect order. So you can type several commands oneafter another without waiting for the first to finish oreven begin.Of course, if you inadvertently type the name of someother command, it will run, with more or less mysterious results.1.3Read-aheadMistakes in TypingIf you make a typing mistake, and see it beforeRETURN has been typed, there are two simple ways to2

1.6On-line ManualOne will be on the day of expiration and the last notification will go out 7 days after the password hasexpired.After one calendar year with the current password,the user will be prompted to change his/her password on the next successful login. The user will berequired to create a password that meets the strongpassword criteria.(See details below.) Also, the usershould make the new password significantly differentfrom the previously used password.The password change utility can be found ds for network accounts:The UNIX Command Reference Manual is kept online. If you get stuck on something, and can’t findan expert to assist you, you can display some manual section that might help on your terminal. This isalso useful for getting the most up-to-date information on a command. To see a manual section, type“man command-name”. Thus to read up on the whocommand, typeman whoand, of course,man man Must be strong.tells all about the man command. If the description Must be changed at least every 365 days for allof a command can not fit in one screen, the man comnetwork accounts.mand will pause after it fills the screen and display May contain upper and lower case alphanumericthe prompt --More--. Depressing the space bar willcharacters. However, due to mainframe restriccause the next page to be displayed. Typing the chartions, the first 8 characters of a password canacter q (for quit) will terminate the display of thecontain only alpha and numerical characters, andmanual information.1the following special characters: # . When acIf your problem is that you don’t know the namecessing the mainframe directly, only use the firstof a command, the man command provides some lim8 characters of the password.ited help. Typing “man-k keyword” causes the system to display short descriptions of all commandsA strong password is achieved by a combination ofwhose short descriptions include the specified keythefollowing factors:word. Thus, At least one letterman -k printwill produce a list of commands that have somethingto do with printing. At least one number1.7 Are a minimum of eight (8) characters. At least one special characterChanging Your PasswordAt Clemson, you set up your initial password at theCCIT Help Desk in the Library. After an initial password has been established, all UserIDs will have a default password expiration setting of one year. Userswill be notified by email prior to expiration that theirpassword is going to expire. These notifications willgo out 14 and 7 days prior to the password expiring. Two more email notifications will go out as well.1.8Multiple Command WindowsIt is frequently convenient to have several xterm windows on your screen at the same time. For example,you might want to use one window to run the mancommand to get a description of a command whileusing another window to try various examples of thecommand you are reading about. This is easy to arrange.1 Actually, the man command uses a general purpose UNIXYou can tell the system to create a new xterm winutility named less to produce such paginated output. Youwill learn more about less later.dow using a “pop-up” menu. If you move the mouse3

2.1into any part of the screen background and depressthe right mouse button, the system will display amenu. Select “Open Terminal”.You can use the new xterm just like the originalone. Each xterm is independent of the others on yourscreen. You can execute different commands simultaneously in different windows.If your screen gets too crowded you can tell the system to “kill” some of the windows you have created.To do this to your new xterm, place the mouse in thewindow’s title bar and press the left mouse button inthe X box on the right.Creating Files — The EditorIf you have to type a paper or a letter or a program,how do you get the information stored in the machine? Most of these tasks are done with a text editor. There are many text editors available on theUNIX system. A popular editor is gedit which is amouse-based editor, similar to editors found on GUIbased systems like Macintosh and Windows. Otherpopular editors are vim, and emacs, which is a fullyprogrammable and customizable editor preferred bymany computer scientists. We will not give a detailedintroduction, but will merely describe how emacs canbe used to create a very simple text file. There is anonline tutorial to help you learn emacs. To take thetutorial, simply type the command emacs and follow1.9 Logging Outthe instructions that appear. Pay close attentionThe remaining sections of this document describe at the beginning of the tutorial. Otherwise, youmany other important aspects of the system. If you won’t know how to get out when you want to.To create a file called “junk” with some text in ithave time you should continue reading them and trying the commands suggested now. When you are using emacs, do the following:done or need to leave, you should performing the fol1. Move the mouse into your emacs window. Unlowing steps to terminate your login session.cover the window if necessary by clicking theDepress the left mouse button in the System menumouse in the title bar.on the screen titlebar. Select Log Out.22. Type control-x followed by control-f.2Emacs should now display a prompt on the bottom line of its window asking for a filename.Manipulating Files3. Type junk and press Return.Information in a UNIX system is stored in files, whichare much like ordinary office files. Each file has aname, contents, a place to keep it, and some administrative information such as who owns it and howbig it is. A file might contain a letter, or a list ofnames and addresses, or the source statements of aprogram, or data to be used by a program, or evena program in its executable form or some other nontextual material.The UNIX file system is organized so you can maintain your own personal files without interfering withfiles belonging to other people, and keep people frominterfering with you too. There are myriad programsthat manipulate files, but for now, we will look onlyat the most frequently used ones.4. Type in several lines of text. Type whatever youwant. End each line by typing Return.35. Save the file by typing control-x followed bycontrol-s.Now create a second file called “temp” in the samemanner. You should now have two files, “junk” and“temp”.2 This is the standard way to read a file into emacs. If thefile doesn’t exist it will be created.3 If you make a mistake, the backspace character can be usedto remove erroneous characters.4

2.2What Files Are Out There?ps -uaNow go back to your xterm window (you might have but the commandto click on the title bar to raise it). The ls (for “list”)ps -u -acommand lists the names (not contents) of any of thefiles that UNIX knows about. If you typeproduces an error message.lsthe response will bejunk2.3tempSo far we have used filenames without ever sayingwhat’s a legal name, so it’s time for a couple of rules.Although you can use almost any character in a filename, common sense says you should stick to onesthat are visible, and that you should probably avoidcharacters that might be used with other meanings.We have already seen, for example, that in the lscommand, ls -t means to list in time order. So ifyou had a file whose name was -t, you would have atough time listing it by name. Besides the minus sign,there are other characters which have special meaning including: \, , , , &, ?, , [, ], and *. Don’t tryto put spaces in the middle of a filename (substituting underscores or periods is preferable). File namesthat begin with a period are treated specially. Theyare not normally displayed by the ls command. Suchnames are intended to be used for files that one normally does not need to be aware of. The -a optionforces the ls command to list all files — includingthose whose names start with periods. If you typewhich are indeed the two files just created. Thenames are sorted into alphabetical order automatically, but other variations are possible. For example,the commandls -tcauses the files to be listed in the order in which theywere last changed, most recent first. The -l optiongives a “long” listing:ls -lwill produce something like-rw-r--r--rw-r--r--1 tom1 tomWhat’s in a Filename41 Jul 22 2:56 junk78 Jul 22 2:57 tempThe date and time are of the last change to the file.The 41 and 78 are the number of characters. tom isthe owner of the file, that is, the person who createdit. The -rw-r--r-- tells who has permission to readand write the file.Options to ls can be combined: ls -lt gives thesame thing as ls -l, but sorted into time order. Youcan also name the files you’re interested in and ls willlist the information about them only. More detailscan be found in ls (1). 4The use of optional arguments that begin with aminus sign, like -t and -lt, is a common conventionfor UNIX programs. In general, if a program acceptssuch optional arguments, they precede any filenamearguments but may otherwise appear in any order.But, be warned. UNIX programs are capricious intheir treatment of multiple options. For example, theps command will accept the options ua as inls -ayou will discover that you have more files than youthought.To avoid pitfalls, you would do well to use onlyletters, numbers and underscores until you’re familiarwith the situation. Finally, don’t forget that casedistinctions matter — junk, Junk and JUNK are threedifferent names.2.4Displaying and Printing FilesNow that you’ve got a file of text, how do you printor display it so people can look at it? There are4 The notation ls (1) means the command ls is describedmany programs that do that, probably more thanin section 1 of the UNIX Command Reference Manual.are needed.5

One simple way is to use the editor. Go back toyour emacs window and type control-x control-f(the find file command) and type junk at the promptfor a filename. What you typed into the junk file willbe displayed in the window. Of course, if the file islarge, only a small portion of it will be visible on yourscreen. When you learn more about emacs, you willlearn to move about in a file — displaying the partsthat interest you.There are several alternatives to using an editor todisplay a file. First is cat, the simplest of all theprograms for displaying files. cat simply outputs tothe terminal the contents of all the files named in alist. Thuswill make UNIX print junk on the default printerassociated with the machine you are using. Optionscan be given to the lpr command to direct its outputto a specific printer. See lpr (1) for complete detailson using lpr.2.5Shuffling Files AboutNow that you have some files in the file system andsome experience in printing them, you can try biggerthings. For example, you can move a file from oneplace to another (which amounts to giving it a newname), like this:mv junk preciouscat junkdisplays one file, andThis means that what used to be “junk” is now “precious”. If you do an ls command now, you will getcat junk temppreciousdisplays two. The files are simply concatenated(hence the name cat ) onto the terminal.cat is less than ideal for displaying large files. Forexample, if you type cat .bash profile the systemwill display one of the files of commands providedto customize your account when you login. You willhave trouble reading the file, however, because it willnot all fit on your screen. You could solve this problem by using control-s to stop cat’s output as described above. The less command, however, provides a better solution. If you typetempBeware that if you move a file to another one thatalready exists, the already existing contents are lostforever.If you want to make a copy of a file (that is, tohave two versions of something), you can use the cpcommand:cp precious temp1makes a duplicate copy of precious in temp1.Finally, when you get tired of creating and movingfiles,there is a command to remove files from the filethe system will display one screenful of the file onsystem,called rm.your screen and then wait for input from you beforeproceeding. Entering a Return will cause one morerm temp temp1line to be displayed. Entering a space will cause lessto display the next screenful. Enter a Q to exit less.In addition, less provides a means to advance multi- will remove both of the files named.You will get a warning message if one of theple screenfuls, search for particular strings or examinenamedfiles wasn’t there, but otherwise rm, like mostthe file in other ways. See less (1) for a completeUNIXcommands,does its work silently. There isdescription.nopromptingorchatter,and error messages are ocThere are also programs that print files on acasionallycurt.Thistersenessis sometimes disconprinter. The simplest is lpr. Typingcerting to newcomers, but experienced users find itlpr junkdesirable.less .bash profile6

3DirectoriesThe next step is to try listing the root of the directory tree. TypeWhen you first made that file called junk, how did thesystem know that there wasn’t another junk somewhere else, especially since the person on the computer beside you could also be reading this tutorial?The answer is that generally each user has a personalor home directory, which contains only the files thatbelong to him or her. When you log in, you are “in”your home directory. You may change the directoryyou are working in — called the current working directory — but your home directory is always thesame. Unless you take special action, when you create a new file, it is made in your current workingdirectory. Since this is initially your home directory,the file is unrelated to any other file of the same namethat might exist in someone else’s directory.A directory can contain other directories as well asordinary files. An easy way to picture this organization is as a (usually big) tree, with your files locatedseveral branches into the tree. It is possible for youto “walk” around this tree, and to find any file in thesystem, by starting at the root of the tree and walking along the proper set of branches. Conversely, youcan start where you are and walk toward the root.Let’s try the latter first. Our basic tool is the command pwd (“print working directory”), which printsthe name of the directory you are currently in. If youtype the command pwd, it will print something likels /You should get a response something like arvmunixvmunix.oldMost of the items named are directories. bin contains the executable files for many of the basic systemcommands; as mentioned above, home contains userfiles; usr contains more system command executablesand local software.Now trycat /home/your-login-id/j

CCIT Help Desk in the Library. After an initial pass-word has been established, all UserIDs will have a de-fault password expiration setting of one year. Users will be noti ed by email prior to expiration that their password is going to expire. These noti cations willCited by: 3Publish Year: 1978Au