<<

University of Manchester School of Computer Science

Introductory Unix Labs Note: the work contained in this document is intended to occupy you for 2 separate sessions of approximately 3 hours in length. Please do not rush through the work. These labs are to introduce you to the Unix and which run on many PCs in the School; some of the information contained in this document is specific to the setup here in the CS school, but most applies to any Unix system. They can only provide a very brief introduction to several aspects of what is a very rich computing environment, but they do point you toward other sources of information, which we hope you will use as a basis for your own extensive independent exploration. The computing environment described here is one in which you will be spending a lot of time over the next few years, so take a good look around and make yourself at home. If you find any mistakes in this document or have any suggestions for improvements or addi- tions, please contact [email protected]. Will you please make sure your work is signed off with a demonstrator for each of the sessions so that we know what you have completed.

26 January 2014 Session 1: Introducing Unix

You have been allocated 2 hours to complete each of the sessions in this document. If you were to rush, you could do all of them in about an hour! But that would be pointless. Although the tasks you are actually doing are trivial (in the sense you are just following a script), unless you take the time to think about them, you will not be able to do similar things when the real laboratories start. In order to be ready for them, you need to practise, and make your stupid mistakes now – when it doesn’t really matter. So please take your time, and spend 2 hours on each session. If there’s anything you feel you don’t understand, please don’t be shy: stick up your hand and ask us! Don’t forget to tell us when you’ve finished each one, or else we’ll think you’re stuck and we’ll waste time chasing you. Actually, this first session is a little longer than the other two, and so will probably take you more than 2 hours to complete.

1.1 What is Unix anyway? An operating system (OS) is a suite of software that makes computer hardware usable; it makes the ‘raw computing power’ of the hardware available to the user. You’re probably most familiar with the and Apple OS X families of operating systems for ‘desktop’ computers, and iOS (Apple, again) and Google’s Android for mobile devices; but many other more specialist operating systems exist, and you’ll be studying some of these and the principles that underpin OS design in COMP25111 in your second year. In the meantime, a potted history of OS development will tide us over... In the late 1950s, an American company called Bell Laboratories decided that they needed a system to improve the way they worked with their computer hardware (it’s probably quite hard to imagine what interacting with a computer without an operating system might be; but it wasn’t pretty and involved manually loading and running programs one by one). Together with the General Electric Company and the Massachusetts Institute of Technology, they set about the design of an operating system they called Multics: the ’Multiplexed Information and Computing Service’. Multics was hugely innovative, and introduced many concepts that we now take for granted in modern operating systems such as the ability for more than one program to run ‘at once’; but it did rather suffer from ‘design by committee’, and the final system was seen at the time as being overly complex and rather bloated (‘bloated’ is all a matter of perspective of course: its sobering to realise though that the entire Multics operating system was only around 135Kb. Today’s operating systems are something like 30,000 times this size...). In the late 1960s, a group of programmers at Bell Labs created a cut-down, leaner and cleaner version of Multics that would work on more modest hardware. Legend has it that this was to allow them to play their favourite (only!) computer game, Space Travel. In an early example of the trend of giving things ‘punny’ names, to contrast with the more clumsy Multics, they called

Introductory Unix Labs 3 Introductory Unix Labs

this new system Unix. The so-called Jargon File is a good source of explanations of various bits of computer slang and their obscure origins, and is well worth a read: in part to give some background history, but mostly as an insight into the minds of the computing pioneers of the past! Even though Unix is now quite old, most Computer Scientists recognise that the designers of Unix got most of the fundamental concepts and architecture right. Given how much comput- ing has changed since the 1960s, this was an astonishing intellectual achievement. Although Microsoft’s Windows is by far the most common operating system on desktop machines, the majority of the Internet, much of the world’s corporate infrastructure, virtually all supercomput- ers, and even some mobile devices are powered by Unix-like operating systems. So, while the polished graphical user interfaces of Windows and OS X appear to dominate the world of com- puting, most of the real hard-core and leading-edge computation relies on an elegant operating system designed nearly 50 years ago (by a team of scientists who wanted to play a game). The history of Unix is complex and convoluted, with the system being updated, re-implemented, and mimicked repeatedly over the years, primarily by commercial companies who guarded their versions jealously. Figure 1.1 shows a tiny fragment of the Unix’s ‘family tree’ (the full diagram is at least X times the size of the portion you can see here). Although many of the branches represent interesting innovations of one kind or another, there are perhaps two that deserve particular attention. The first of these was the decision by Apple some time around the turn of the millenium to drop their own—highly popular, but aging—bespoke operating system (unimaginatively called Mac OS 9) in favour of a Unix-based system (now the more familiar ‘OS X’, where ’X’ is both the Roman numeral ‘10’ and a nod in the direction of the uniX nature of the OS). Although the majority of Mac users are blissfully unware of the fact, behind the slick front-end of OS X, sits a variant of Unix. The second, and perhaps more profound of these events was the creation in 1991 by Finnish programmer Linus Torvalds of a Unix-like system, the source code to which he gave away for free1; this became known as the Kernel. Combined with other created by the , a non- commercial version of Unix called GNU/Linux was born (GNU here is a recursive acronym for “GNU’s not Unix”, a swipe at other commercial non-Free versions; much to the annoyance of the Free Software Foundation, GNU/Linux is almost always called just ‘Linux’2.) Linux has been, and continues to be, developed cooperatively by thousands of programmers across the world contributing their effort largely free of charge. It is amazing to think that such a project could ever happen – and it is surely a testament to the better side of Human nature. But what is interesting is the observation that these programmers are not motivated by commercial concerns, but by the desire to make good reliable software and have it used by lots of people. Thus, Linux is a good choice of Unix: it’s Free, it’s efficient, it’s reliable, and it is now used by large corporations, governments, research labs and individuals around the world. Even Google’s Android platform is a Linux-based mobile OS, and the Amazon Kindle is also a Linux box behind its user interface. One of the results of the fact that Linux is Free is that several organisations and companies have created their own distributions of it; these vary a bit (in fact, anybody is free to make any change they like to Linux, and pass it on to whoever wants it). The distribution we use in this School is Scientific Linux, a clone of Red Hat Enterprise, which is the most widely used distribution

1. ‘free’ here in the sense both of ‘freedomto reuse or adapt’, and also in the sense of ‘without charge’. 2. Linux is pronounced “Linn-ucks”, despite the fact the name was coined by its creator, and his name ‘Linus’ is pronounced “Leen-uss”! Session 1: Introducing Unix 4

Figure 1.1: A fragment of Éric Lévénez’s Unix History chart, reproduced with permission and showing the beginnings of Linux in amongst other versions of Unix. of Linux in industry. So, if you are to become an expert computer professional, it is important that you understand the theory and practice of Unix based systems. Learning Unix is not only a crucial skill for any serious computer scientist, it is a very rewarding experience.

1.2 School Unix network The School has well over 1000 PCs running various versions of the Unix operating system, nearly 300 of which are used for undergraduate teaching; most of these are ‘dual-boot’ ma- chines which are also capable of running Windows, The machines are all connected by a net- work, so that you can sit at any machine and it ‘knows who you are’ – more about this later. This introduction is primarily aimed at the use of the Linux version of Unix on PCs.

1.3 User Names To use a PC, you first have to identify yourself by typing your user name and password. These are the same as your campus username and password that you use for Windows machines.

1.4 Reading this document In this document, things that you have to type appear in a typewriter font (like this), to distinguish them from prompts from the machine, which appear in 5 Introductory Unix Labs

a bold sans serif font (like this). They won’t actually appear like this on your screen. Remember to press  , called the Return key, after each command. Things that appear between angle brackets () are descriptions of things to type rather than the actual characters you type. Hopefully this will all become clear as we go on. Also, by the way, watch out for getting mixed up between a lower case el, l, and a digit one, 1 – unfortunately these two characters look very similar in many fonts!

1.5 Loggingon The machine should be displaying the login prompt, which will look something like E-C07LF16001 login: If the machine you are using is dual-boot and is running Windows, follow the instructions displayed on the lab wall to reboot into Linux. (E-C07LF16001 is just the name of the machine displaying the prompt, yours will probably be different). Note: If you use the numeric keypad to the right hand side of the keyboard during the following sections, you must use the ‘num lock’ facility to input numbers. Now type your user name, e.g. mXXXXXXX  Whether you typed your user name correctly or not, the machine will now ask for your password Password: You now have to type your password for you campus username. Note that when you type your password, nothing will appear on the screen, not even *’s. This is to prevent anyone looking over your shoulder seeing your password, or even how long it is. If you make a mistake either in the user name or the password then you must type both your user name and your password over again. If your password seems not to work after several tries, ask for help. When you have logged in, you will get a prompt, which looks something like [mXXXXXXX@E-C07LF16001 ~]$ except you will see your username before the @ and the name of the machine you are using after it. Carefully type the command /opt/scripts/copybashdotfiles and press Enter. This will copy into your filestore various ‘dotfiles’ to make your account easier to use. Now log out, by typing d that is, hold the ‘Control’ (or ‘Ctrl’) key down and press ‘d’, then release ‘Control’. Now log back in again (but don’t type anything else yet). When you have successfully logged in, the machine responds with assorted information, and then prompts you with something like: Session 1: Introducing Unix 6

Manchester University, School of Computer Science Linux Desktop Switcher

Your desktop is currently set for: AnotherLevelUp Fvwm95

Please choose your desktop from the list below:

Continue to use AnotherLevelUp Fvwm95 1 UseAnotherLevelUpFvwm95 2 UseGNOME 3 UseKDE 4 UsxAfterStep 5 UseWindowMaker 6 UseAnotherLevelUpLesstif(Mwm) 7 UseEnlightenment 8 UseFVWM(vanilla) 9 Usetwm

C Consolelogin I Start X Interactively(pick from available screens or layouts) R StartXWithwindowmanageronaRemotehost Enter choice:

This is thelistof Window Managers you can chooseto useunder X-windows. For the moment, we don’t want to go into X-windows, so type  to choose the simple console interface (an upper or lower case C will do here). The machine now gives you a prompt, which will be something like mXXXXXXX-) to show that it is waiting for you to type a command.

1.6 Commands Typing a command causes a program to run which does what you told it to do (not necessarily what you meant it to do!). For instance, date is a program which displays the current date and time. Type date  to see the date in a default format. Now Type date -d +1day  to see what the date and time will be tomorrow. Type date +%d/%m/%y  to get just today’s date in the normal format. fortune is a classic Unix ‘game’, that simply picks from its huge database, a phrase typical of those found in ‘fortune cookies’, and displays it for you. Now try typing 7 Introductory Unix Labs

fortune  A useful thing to remember is that typing  repeats the last command (don’t forget that is a description of what you type – if you have just typed a left angled bracket you are not concentrating: go back to the start!) Do this a few times to get a selection of ‘fortunes’. Now type several times without pressing  until you see date -d +1day again: each time you key you are stepping back through your command history, one command at a time. You can go forward again by typing – try this. Now find the date -d +1day again, use to step the cursor to just after the 1, then delete the 1 and type a 2 instead, then press the  key. Now log out, by typing d that is, hold the ‘Control’ (or ‘Ctrl’) key down and press ‘d’, then release ‘Control’.

1.6.1 What happened there? Now a quick explanation of what you’ve just done. You have been interacting with a . A shell is a program that prompts the user for commands, accepts them, executes them and displays the results. Unix has many shells: the first was called the ‘Thompson’ shell (also known as just ‘sh’, and pronounced “shell”), written by Ken Thompson for the first Unix system; then came the ‘Bourne’ shell (also called ‘sh’), written for a later commercial version of Unix by Stephen Bourne. You have just been using the Free Software Foundation’s ‘Bourne Again’ shell (another pun-name taking a dig at its commercial fore-runner), or ‘bash’. The various different shells offer the user different facilities: ‘sh’ is rather primitive compared to the more modern ones. However, their basic functionality is always the same: they accept commands from the standard input (for now, we can treat that as meaning ‘the keyboard’), execute them, and display the results on the standard output (i.e. for now ‘the screen’, which in this case was the entire screen, or console). Shells repeat this process until they have reached the end of their input, and then they die. d is the standard way of marking the end of the keyboard input file in Unix. So when you typed it, the bash you were talking to ended, and you were logged out. The use of and to browse the command history are examples of facilities offered by ‘bash’ that are not in the original ‘sh’. Unix shells are rather like Command Prompt windows in Microsoft Windows, except that Unix shells are more sophisticated.

1.7 A simple shell ‘program’ We shall now give you a taste of the sophistication of shells. Login again, and select console login as before. When you get the prompt, carefully type the following lines, exactly – position of spaces and the case (upper or lower) of letters is significant. while read name; do  if test "$name" = "$USER"; then echo "Welcome $USER"  else echo "Who?"; fi  done  Session 1: Introducing Unix 8

If you make a mistake, type c and start again. After each line, the computer should prompt you for the next line with a simple > ; if not, then you have made a mistake. When you have successfully typed these lines, the computer should simply be waiting for you to enter a name. So now type a name (e.g. your first name) and press  . The computer should respond with Who? You can do this several times using different names, but at some point you should enter your user-name. In response to this, the computer should display Welcome mXXXXXXX (except with your user name). When you get bored with running this first ‘shell program’, you can end it by signifying the end of its input (you know how to do this don’t you?). Your prompt should reappear. Now logout. That was a rather contrived example, but it does show a tiny bit of the power of bash, which pro- vides a language in which we can write programs to perform common tasks using programming constructs such a ‘loops’, as we have done in the above example. Real experts write command line programs like that quite often, when there is a single one-off job to be done. However, for more complex programs, or ones which may be needed more than once, it is usual to place the commands in a file, called a shell script. This is similar in idea to the Windows batch file but much more powerful. If you would like to know more about bash, then at some point (not now) you should run the command man bash.

1.8 Where’s the GUI? Its quite possible that today is the first time you’ve interacted with a computer in this way: al- most every modern machine boots up ‘out of the box’ into an attractive graphical environment that allows you to ‘get going’ with a minimum of fuss. Whether you’re used to using Win- dows, or Macs, or even Linux machines, it’s likely that you have done so via a , so you’ll be very familiar with the ‘WIMP’ (Windows, Icons, Menus and Pointer) paradigm, even if you didn’t know it had a name. The point of WIMP systems—and in fact of Graphical User Interfaces generally—is to make computers easy to use without having to learn much of what is happening behind the scenes. They are designed to allow human intu- ition to help with the process of using what is in reality a complex and sophisticated piece of hardware. The principle behind most GUIs is that of ‘direct manipulation’, the idea being that if you present concepts to a user in a consistent manner that to some extent reflects how you would expect things to happen in the ‘real world’, then your intuition will help you learn how to do things that otherwise you’d have to look up in a manual. In a direct manipulation inter- face, you have such things as ‘files’ and ‘folders’ and ‘trash bins’, all of which have real-world counterparts: so you instantly know that a ‘folder’ is a handy way of collecting ‘files’ together, and that when you don’t want them any more you put them in the ‘trash bin’. When you want to resize a ‘window’, you ‘grab’ it with the mouse pointer, and just drag a bit of it until it’s the size you want: in other words, you manipulate things ‘directly’ in the GUI, and these manipulations are translated into much lower level changes that take place in the machine’s memory, CPU, or hard disc. As a computer scientist, there are many upsides of using GUIs; like everybody else, we want to be able to do everyday things with our computers: browsing the web, reading email, watching films, and the GUI undoubtedly makes this easier. It also means that your intuition, and the little bit of ‘learning’ that you did to get to grips with the idea of the GUI transfer well from one GUI to another; Macs, PCs and Linux boxes all have interfaces with similar enough graphical paradigms that it won’t take you long to work out how to use them. But as computer scientists, 9 Introductory Unix Labs

rather than ‘casual users’, we want to be able to do much more, so the downside for you is that a lot of the things you really need to understand about the behaviour of the underlying machine gets hidden by the GUI (and there are also many tasks that are better achieved without using a GUI at all). The problem you’ll have to come to terms with is that, having grown up with GUIs, it will for some considerable time, be tempting to turn to the GUI whenever you want to do anything. It will, after all, feel familiar and ‘easy’. Learning the alternative will be, by comparison, quite hard, and doing things a different way may feel crude, messy, convoluted, esoteric and prob- ably quite unpleasant at first. But trust us; going beyond the GUI is a crucial skill to being a successful computer scientist, and a vital part of your learning here in the School. The first thing to understand here is that a computer’s graphical environment is not a funda- mental part of the machine; it’s just another program running ‘on’ the operating system. In the case of Windows and OS X, as well as mobile devices, you don’t get much choice in terms of the look and feel of the GUI (apart from making trivial changes like tweaking the colour scheme, or changing the ‘desktop ’). But this is just because the companies behind these systems have opted for ‘consistency’ rather than ‘flexibility’, and not because of anything technologically fundamental. For systems aimed at the casual user, this is a very sensible thing to do; imagine how horrible it would be trying to provide support over the phone to someone when you first have to understand what kind of GUI they have – at least with consistent GUIs you have some idea where to start. In the case of Linux—which is somewhat less designed for casual use—there is far more flexibility in the choice of GUI, and we’re going to use this to explain some important fundamental principles. Okay, time to try it out – you need to login again. login:  Password: ...  Then you get asked what kind of interface you want. Check which (or ‘desk- top’) is being listed as your current setting. It should be AnotherLevelUp Fvwm95, and if it is then you need now only type  . If some other desktop is your current setting, then you first need to type 1  to select AnotherLevelUp Fvwm95. N.B. If you have used Linux before, and recognise your favourite desktop on the list, please use option 1 anyway for these introductory exercises; you will discover why later.

1.9 The Linux Graphical Environment Linux itself has no graphical environment, and relies on a program called the Xserver to com- municate with the graphics hardware in order to display anything on the screen beyond the crude ‘terminal’ view you’ve already seen. To get a ‘desktop’ environment, we also need to run a window manager (in this case AnotherLevelUp), which deals with creating and drawing the familiar windows and icons of a desktop GUI. So when you selected something from the Desktop Switcher a moment ago, two things happened: first, the Xserver was started, and then the appropriate window manager. The ‘layering’ of these programs is shown in figure 1.2. This division of functionality into layers is a common architectural pattern that you’ll encounter over and over during your studies. The AnotherLevelUp was developed in the School by John Latham as an improvement on Red Hat’s AnotherLevel. In practice AnotherLevelUp Fvwm95 is just a Session 1: Introducing Unix 10

configuration of a window manager called FVWM which in turn runs on top of an X Server which provides the basic display and interaction facilities.

User Applications

Window Manager Configuration

Window Manager

X Server

UNIX/Linux

Figure 1.2: The layered structure of Linux’s graphical system, with software nearest to the underlying hardware at the bottom, and software closest to the user at the top.

All this flexibility and ultimately freedom of choice for the end user results from X windows having a good architectural model, with clear differentiation between the various layers in- volved in the whole process. Indeed it is even possible (in many circumstances) to change the window manager without shutting down existing applications running on top of it; let alone logging out or rebooting the machine.

1.10 Why AnotherLevelUp? The most commonly used desktop environments in Linux are GNOME and KDE; these are extremely sophisticated GUIs, and considerable design effort (both technical and artistic) has gone into making them easy and pleasing to use. The danger, for now, however is that they are, well, a bit too easy and ‘familiar’ for what we want to achieve here—which after all is to help you understand what is really going on ‘behind’ the GUI. AnotherLevelUp is specifically designed with this in mind, with deliberately exposed features intended to provoke constructive thought about the way the computer is used, to encourage you to do things differently to what you’ve done in the past in a way that teaches you more about the fundamental principles of computer science. Every time you come across something that is different to your existing experience you should resist the desire to wish it was the same and recognise the benefit of the difference on your mind. AnotherLevelUp is much more ‘raw’ than anything else you are likely to have used; perhaps in some ways much more ‘primitive’; and certainly less ‘graphically designed’. This is intentional. 11 Introductory Unix Labs

1.11 An introduction to AnotherLevelUp A number of windows and icons should have appeared on your screen, which should now look something like figure 1.3. There are 4 obvious windows on your screen (you may not be able to

Figure 1.3: AnotherLevelUp’s screen layout

see them all), and a few other items which are, in fact, also windows. The 4 obvious windows are: • A welcome screen from AnotherLevelUp. Read the contents and then dismiss it. You should not see it again, but you will want to find out about themes later. • Firefox and Thunderbird you will use these for web browsing (Firefox) and email (Thunderbird). For now we shall hide these two windows in the task bar at the bottom of the screen. Find the 5 little square buttons on the right side of the title bar right at the top of one of these two windows. You may have to move the pointer over the window and wait for it to come to the top, if it isn’t already on top. Position the pointer on the middle one of the 5 little square buttons, that is, the one with a little line near its bottom, and then click the left mouse button. This should cause the window to hide. Repeat this for the other window. • – this is the right hand one of the two remaining big windows. This window is running a bash and you will use it for giving commands to be executed, just as you did in console mode before. As an example, move the pointer into the xterm window and type the fortune command. Run the command again (hint: you don’t need to retype it!). Now run date -d +2day using only the arrow keys and return. • Nedit – this is the left hand one of the two big windows.Its title bar should say Untitled. Nedit is a text editor which you will use for manipulating text (for example, programs or reports). You will learn how to use this in a later practical session. (It is labelled Untitled because you are not currently editing a file: in general it places the name of the file you are working on in its title bar.) The remaining windows on the screen are Session 1: Introducing Unix 12

• Task bar – this is the strip along the bottom of the screen, which looks rather like the task bar in Windows. The important difference is that this is actually a window, and can be killed or hidden, etc.. • Load monitor and pager – these are the three squares near the top right corner of the screen. The left square is the load monitor: it continually shows a graph of the computer’s load average. However, because Linux is so efficient, and processors are so fast, it may appear to just be a blank square much of the time! The square to the right of this is labelled with your user name, and has 4 smaller squares inside it, 3 of which are (currently) just blank. To the right of this is another square containing 4 smaller squares which is labelled Desk 1. These two squares together are called the pager, and they give you access to 2 desktops each containing 4 pages. You will explore these in a moment. • Xdaliclock – this is a clock. If you click on the button to the left of it, a larger clock will be made. Later you can find out how to choose a different kind of clock, or switch the clock on and off. • Menu button panels –there are 6 of these on the right of the screen. They are conve- nient versions of 6 of the most used menus in AnotherLevelUp.

1.11.1 Desktops, pages and the Pager Have a look at the pager. Move the pointer into the bottom right hand square of the 4 smaller squares of the desktop labelled with your user name, and click the left mouse button. Can you guess what has happened? Apart from seeing the most obvious change, you should also notice that the square you clicked has turned to pink. Now move the pointer to the middle of the left of the screen and try to push it off the screen. After a short pause, the pointer should flip to the right of the screen; and inside the pager, the bottom left square should be the one that is pink, instead of the bottom right one. Now can you guess what’s happened? Finally, move the pointer to the middle of the top of the screen and try to push it up further. You should now be back where you started, and you should have figured out that your desktop has 4 pages. Have a little play around with switching the pages, by both methods, before continuing. Note that this very useful and powerful feature of page scrolling via the mouse does mean you will need to treat your mouse with some respect! E.g. casually bashing it out of your way might be likened to randomly twisting the steering wheel while driving a car! Like all the features that are new to you here, it can be switched off or modified via the preferences menu. But the whole point of them being enabled by default is to expose you to new ideas, so please don’t short-change yourself by hastily disabling them! Now try this: press and hold the ‘windows’ key at the left of the keyboard, and also the Con- trol key. Now use the arrow keys to step around the pages of the desktop. Then try using the ‘windows’ key with the Shift key and the left/right arrows to change desktops. Try the pages of your second desktop, the one labelled Desk 1. Notice what happens to the task bar when you go onto the other desk. A handy feature of desktops is that the task bar only shows windows which are on the current desktop, or are hidden (like your Firefox and Thunderbird windows should be now). This means you can have a large number of windows open at any time, without having to clutter up your task bar, if you organise them sensibly onto separate desktops. In FVWM, you can in fact have as many desktops as you like, each with as many pages as you like. In AnotherLevelUp the default is 2 desktops each being 4 pages big, as that is a good 13 Introductory Unix Labs

starting point for you. Later you can find out how to change this. You should think of good ways to use the different pages and desktops, for example you might be working on a laboratory exercise on one desktop, while waiting for your previous one to be marked on another. Meanwhile, to get you started, go to the first page of your second desktop and unhide your Firefox and Thunderbird windows by clicking on their buttons in the task bar. If, in a few weeks time, you are still using just the first page of the first desktop with lots of cluttered windows, you are letting yourself down. Please make a conscious effort to use features which you have not been used to, both for your convenience and to broaden your mind. Now go to the first page of your first desktop.

1.11.2 Menus Move the pointer to anywhere on the blue background but preferably not near to the right hand edge of the screen. The background area is known as the . Now click the left mouse button, and you should see the main menu. You can also get this by pressing the Main button on the task bar. You will see a number of choices, some of which have a little rightwards pointing arrow next to them: these indicate sub-menus. Move the pointer around the menu to see these sub-menus pop up, but don’t click on anything yet. If you are used to using Microsoft Windows, you may find yourself using the Main button to get the main menu, even when there is plenty of uncovered root window. Really, the Main button is available in AnotherLevelUp as a convenience for those times when the root window is completely covered. Otherwise it is much easier to left-click on the root window. Not only is that likely to be nearer to the current mouse position, but once the menu is up you will find the mouse is usually already at the top, where the most commonly wanted items are.

1.11.3 Making new windows Now click on the option labelled New Shell, it will be near the top of the main menu. A transpar- ent box will appear with its top left corner under the pointer: you are in the process of creating a new shell window, an xterm. In general, when you create a new window, AnotherLevelUp will do one of 3 things: • If there is room for the window without it having to be on top of any existing ones, it will just make it appear in such a place. • If the window has a fixed place to go, it will make it appear in that place (e.g. the task bar will always appear at the bottom of the screen). • If neither of the above are true, it will produce a transparent box so you can choose where the window should go. It’s this third one that’s happening now. Move the pointer to somewhere convenient (e.g. near the top left corner of the screen?) and the transparent box will follow. When you’re ready, click the left mouse button and FVWM will create the new window. This is a shell window, so it’s running bash: try running a fortune command in it.

1.11.4 Window and window raise By now you have probably noticed that AnotherLevelUp by default uses auto focus and auto raise. This means when you move the mouse into a window, you do not need to click in order for that window to get keyboard focus and raise to the top, if there are other windows partially covering it. This is deliberately different to what you are used to – remember the idea that the Session 1: Introducing Unix 14

environment is designed to provoke you to think. Both of these features can be altered if you so desire, but don’t do it just to get back what you are used to. You should try them as is for a few weeks. After that you might decide to switch off auto raise, or slow it down, but, say keep auto focus. You can even set it so that clicking in the window does not cause it to raise! If you wish, you can change focus without using the mouse. Try holding the Microsft key at the left of the keyboard, and use the arrow keys to select a window in that direction. After a while, you’ll find this far more intuitive than the usual Alt-tab method (which is also available). Another thing you should learn, for when you are using the mouse to select windows, is this. When you right click in the middle of a window title it will bring that window to the top, or if it is already at the top, it will send it to the bottom. This is handy if you have allowed your page to get a bit cluttered and you want a window which is totally obscured by another – simply send the obscuring one to the bottom. Try it now – move your new shell window so it is over another first. Actually, this is such an important feature that you should probably right it down somewhere! Particularly if you decide to keep auto raise, and you prfer to use the mouse rather than short cut keys, it is only a matter of time before the window you want is obscured....

1.11.5 Window hide, maximise and close buttons and task bar buttons Like most windows, the new xterm you have just created has 8 buttons on its title bar, 3 on the left, and 5 on the right. (The left most button on the left appears as a little picture.) For now, we shall examine the 3 most commonly used ones, which you should recognise from Microsoft Windows. Of the 5 on the right, you’ve seen what the middle button does (if you can’t remember, you’re going too fast!). Using the left mouse button, click on the window title button to the right of the middle one and see that it makes the window grow to fit the full screen. Now click that same button again, and the window should return to its original size. Using the same method as you’ve used before, hide this window. The window should disappear, but it’s not dead. Down on the task bar you should see two buttons labelled xterm and 1 Xterm. If you don’t, then perhaps you closed the window instead of hiding it (i.e. by pressing the wrong title bar button!)? If so, create another one and try again. It’s time to briefly explain those Xterm window titles. When Xterm windows are first created, they are given the title xterm, except for the ones which are made for you when you login: currently there can be up to 3 of these, labelled 1 Xterm, 2 Xterm and 3 Xterm respectively. As you will see in the next session, the titles of Xterm windows change in a useful way while you use the windows. Right now, the button in the task bar labelled 1 Xterm corresponds to the Xterm window you had to start with, and which should be still visible. The button labelled xterm corresponds to the one you’ve just hidden. Click on both these task bar buttons several times, with each of the 3 mouse buttons (left, middle and right) in turn, watching carefully what happens. Make a note of what each mouse button achieves when it is used to press a task bar button. End up with both visible on the screen. Now move the pointer to the right-most of the 5 small buttons on the right of the new xterm window and click it (using the left mouse button). That was the Close button – the window is now dead, and gone. There should be only one xterm button on the task bar now. 15 Introductory Unix Labs

The window you just closed was running bash, which is a shell. That means you also know another way you could have ended it – what is it? Create a new shell window, move the pointer inside it, and then, without using the mouse, close (i.e. end) the window.

1.11.6 Exploring the main menu Get the main menu up again. The next two options of the menu create a new Nedit and Fire- fox/Thunderbird windows in a similar way to xterm so ignore them for now. There are some sub-menus that we shall not explore in detail in this session. We just mention them here so you can explore them yourself when it is appropriate. They are: • Java bugs work arounds – this is an experimental set of features which might help tackle some of the problems encountered from time to time with Java programs. It remains to be seen how useful it is, but don’t worry if right now it looks like complete gibberish! • ARCADE – ARCADE is the name of the coursework management system we use here, and from this menu you will be able to look up your details, including coursework marks. This may not be set up yet, but you should familiarise yourself with it later when it is. • Shell browser and Favourites – this menu offers two related features. Whenever you start a program from the Other programs menu (see below) AnotherLevelUp keeps track of it for you, and offers a menu of your favourites organised by frequency as well as your most recent 10. In addition, you can set up your own items to be added to this. The second feature allows you to browse through your file-store and choose a directory (what windows calls a folder) at which you want to start an xterm. This is then added to your favourites menu. • Preferences – this menu allows you to configure a wide variety of things associated with your desktop including colours, mouse behaviour etc.. More about these shortly. • Other Programs – this is a set of nested menus from which you can start various programs. The same menu can also be obtained by clicking the right mouse button on the root window. This menu is actually generated automatically from the software installed on the machine, so it may be a little odd in places. Whenever you start a program from here, it is added to your set of favourites, which makes it easy to find again. • Desktop Utilities – The option labelled Desktop Utilities offers a sub-menu of items each of which relates to a utility of your desktop. Typically, each can be started or stopped as well as being configured. At some point you should explore these, but not just now.

1.11.7 Device and File Browser The option labelled Device and File Browser pops up a sub-menu which allows you to start a file browser and also access devices such as USB, CD/DVD ROM.

File Browser In this sub-menu, the option labelled File Browser starts a file browser. Try it. After a short pause a file browser window will appear under the mouse, as a transparent box, with FVWM waiting for you to place it on the screen. You should find a convenient place, and click the left mouse button. Now close this window from its file menu. Session 1: Introducing Unix 16

Now the big question: are file browsers a good idea? Certainly, everyone should agree that they are, in general, a good idea for the non-expert user. Whereas for experts, they are often much slower to use than command line oriented approaches like the Unix shells. And we believe that using a file browser all the time would hinder your understanding of what is really going on un- derneath: and as a Computer Scientist, it is most important that you gain that understanding as soon as you can. Of course, if your only choice was between a Windows Command Prompt win- dow or Windows/Internet Explorer, then, it would be understandable to use Windows/Internet Explorer all the time. (Although Command Prompt is slowly catching up with power of bash.) Our continued advice to you is that you should resist the temptation to simply ‘transfer your previous experiences’ to Linux/Unix: you will miss out on so much that is important to you.

1.11.8 System Utilities The option labelled System Utilities offers a sub-menu of various interesting things. Choose the option labelled Top. If this gives you a sub-menu of two options, choose the one labelled Top (in ). This creates a window similar to an xterm (it’s actually called rxvt) but instead of running a shell, it’s been set up to run a Linux (Unix) command called top. This displays some system information, and then a continually updating chart of the jobs, or processes, currently running on the machine, presented in descending order of how much of the processor time they are using. You’ll see lots of processes owned by a special user called root, and we are certainly not going to explain all that here! You should see some owned by you, in particular, it may well be that the process right at the top of the list is your top command itself - that’s because your computer is hardly doing much at the moment. If you move the mouse about a bit, you might see a process called X jump to near the top – that’s the X server! When you get bored, close this window. Over a period of time, you should familiarise yourself with the other options on this sub-menu, by experimenting, but not just now. An especially useful one, at the bottom, allows you to produce a picture of a window which is on your screen, and send it straight to the printer.

1.11.9 Window Operations Take a look at the Window Operations sub-menu. The way this generally works is that you first pick the option, and then you pick the window you want to apply the option to. Choose the Move option – the pointer should change to a sort of cross shape. Now move the pointer into the xterm window, press (and hold) the left mouse button, and you can move that window around, until you release the button. Now try to resize a window, using the option labelled Resize. With a bit of guesswork, you should be able to figure it out (don’t forget to ask for help if you need to!). These operations allow you to organise the windows in a way which is convenient. There are plenty of other options on this sub-menu – you can experiment later. For now, try out another way of using the menu: move the pointer to the middle of the xterm title bar and click the middle mouse button. The Window Options sub-menu appears again. When you use it this way round, you have already selected the window you want it to work on, so you just pick the operation to apply. Use this to move the xterm window around a bit again. Actually, instead of using the middle button on the middle of the title bar, you can select the same menu by pressing the left mouse button on the little picture at the very left of the title bar. In case you don’t like having a little picture there, later you can find a way of changing it to an 17 Introductory Unix Labs that more suggests it is actually a menu button. Now try pressing that button on the xterm window. In fact, an even quicker way to move a window around is to press (and hold) the left mouse button while the pointer is on the middle of the window’s title bar! Try it. There’s even a quick way of resizing: move the pointer to the very edge of a window until it turns into a little arrow pointing straight out of the window. Now press (and hold) the left mouse button, and move the pointer. Now try this at a corner of the window – even better? Play with all these until you feel familiar with them. And as if that were not enough, try holding the ‘windows’ key at the left of the keyboard and pressing R for resize, or M for move. Try holding the ‘windows’ key and the Alt key and then pressing one of the arrow keys!

1.11.10 Ending windows When you want to end (that is, close) a window, if the window has its own method to do this, you should always use it. For example, Firefox has a menu called File on which there is an Quit option – more about that later. So whenever you want to exit Firefox, it is better to use its Quit option than to use the Close button of its title bar. The reason for this is simple: software written for Linux comes from thousands of different sources around the world, and obviously different programmers can have different ideas of what their programs should do when given various Signals by a window manager. When you press the Close button on a window, the window manager sends a particular signal to the application that is running in that window, hoping it will shut down gracefully. You cannot be sure that the programmer who implemented that application was expecting his or her program to receive that particular signal as a means of being told to end, so it may not cause the program to end properly (e.g. an editor might not save the file you were editing). But you can be more sure that the application’s own exit mechanism will work properly, as that was written by the same programmer (or one from the same team) that wrote the rest of the application. The collective understanding between these different programmers is becoming more coherent and consistent, and over the past few years this problem has seriously reduced. However, it is best to play safe. When a program has no exit mechanism of its own, or for whatever reason, it is failing, you can use the Close button of its title bar, if it has one. If this doesn’t work, or the window does not have a title bar then you need to use one of the following methods. You’ll notice on the Window Operations sub-menu that there are three options, called Delete, Close and Kill. These get rid of a window, but they are slightly different: • Delete – this invites the window to exit gracefully, but it might refuse to. This is the safest of the three. • Close – this invites the window to exit gracefully, but if it refuses, it gets killed anyway! (This is the same as the Close button on the window’s title bar, if it has one.) • Kill – shoot first, and ask no questions:thisjust killsthe window. This can be dangerous and should be used only as a last resort. Whenever you use these options, you should bear these differences in mind, and be careful. For example, if you Delete an editor window, it’s likely (but not guaranteed) that it will save your work before it dies gracefully, whereas if you Kill it, it won’t get the chance. In general, Session 1: Introducing Unix 18

only use Kill after you’ve tried Delete, and it has failed. It is almost always preferable to use an application’s own exit mechanism if one exists. You should now practise manipulating, creating and deleting windows on your screen until you are confident that you can arrange the layout of your screen at will.

1.12 Communicating with others The time has now arrived to look at ways of communicating with the other people in the school and the outside world. We will look at two ways of doing this: • EMail: This is the major means of communication within the school. • The Web. There are many different tools for reading and creating and for web browsing, and many users have their own particular favourites. For the moment we expect you to use Firefox and Thunderbird.

1.12.1 EMail You should have Thunderbird on your screen – if you have followed this section carefully then it will be on the first page of your second desktop. Got to that page. (If you cannot remember how to do this, you are going too fast – go back and find out!) If you don’t have a Thunderbird running for some reason, start one now by selecting the New Web Browser main menu option. This (currently) actually starts both Firefox and Thunderbird. Alternatively, you could just type thunderbird  in an xterm. You should also have Firefox on your screen. Use it to go to https://wiki.cs.manchester. ac.uk/index.php/How_to_set_up_Office_365_Mail_in_Thunderbird which is a docu- ment written by fellow students telling you how to set up Thunderbird! Please follow all those instructions carefully, asking for help if you need it. Now that you have successfully set up Thunderbird, let’s explore it a bit. To access your mail from the mail server, you click on the Get Mail icon. Another small win- dow then appears asking you for your password3. For convenience, Thunderbird has probably already done that bit when you started it. Enter your normal Unix password in the box and click on the OK button when you are happy that it’s correct. Any new mail that has arrived since you last checked will appear in the mail browser window. You can read mail messages by clicking on their summary lines. You can also sort the messages by Subject, Sender or Date by clicking on the appropriate button above the summary lines. Once you have read a piece of mail and decided that you don’t want to keep it you should delete it by clicking on the Delete icon. However, this doesn’t completely get rid of the message, but transfers it to a mail folder called Trash from where you can retrieve it if you delete a message by accident. To clear the Trash folder, which you should do regularly, select the Empty Trash menu item on the File menu. If you don’t do this regularly your allocated disk quota might get used up by old mail messages. You can reply to a message or forward it to another person by using the appropriate icons in the mail browser window. To send a new message of your own use the Write icon. Just fill in the mail

3. This is because Firefox uses a protocolcalled IMAP to access your mail from a mail server and the password is required for security purposes. 19 Introductory Unix Labs

address of the recipient and the subject line. Once you have finished composing the message just click on the Send icon to send it. Try sending a message to a friend or someone sitting near you in the lab. Should you decide not to send a message once the composition window is up, you can select Close from the window’s File menu. If you receive mail from someone whose address you might want to use later, you can add their name to an Address Book by right clicking on their email name. You can then refer to the address book when composing messages by using the Contacts icon on a composition window. Thunderbird is itself quite configurable, and remembers most settings you make. You can change the size of the various windows, change the position of the split between multiple parts of one window, make it remember your password so you don’t have to enter it each time you read your mail, and so on. Rather than overload you now with details, you are encouraged to explore the Thunderbird menus over the next few weeks.

Email is important It is important to realise that email is one of the major means of communication in the school, so make sure you follow these rules:- • Read your email regularly, at least once a day. • If you don’t receive email and suspect that there may be something wrong with your email setup, Do Something About It Quickly, don’t just ignore the situation. Amaz- ingly, every year there are some students whose email stops working, they do nothing about it, and get themselves into a serious mess when they have missed important an- nouncements, meetings and deadlines.

1.12.2 The Web Every document and resource on the Internet has a unique address known as its uniform resource locater (URL). A URL is made up from the document’s name preceded by the hierarchy of directory names in which the file is stored (pathname), the Internet domain name of the server that hosts the file, and the software and manner by which the browser and the document’s host server communicate to exchange the document (protocol). It’s a good idea right now to go to the web page for this course and bookmark it. You can do this as follows. Go to http://studentnet.cs.manchester.ac.uk/ugt and make this your home page. You should add it as a bookmark as well. The find Study & Curriculum and then Syllabus which should take you to a long list of courses. Under Service courses you will find COMP00900 – that is the course code we use withing CS for this course. (For some reason!) There are two links of interest Materials and Syllabus. Probably the former is the most interesting right now – select it and bookmark it. Those of you who are interested can find lots more information about Linux at the Linux Doc- umentation Project web pages, which can be found at http://tldp.org/.

1.13 RTFM This is a frequently used Computer Science acronym. It is said to stand for ‘Read The Flipping Manual’ (or something similar). Session 1: Introducing Unix 20

You will already be aware that there are lots of things to know about Linux and computers in general, far more than you have encountered so far, and you will not remember it all. Fortu- nately, there is lots of documentation available and you should get into the habit of knowing how to use it properly. We expect you to explore computer related topics using self learning techniques. This will be important not only to succeed in the course but also in the rest of your career. The information you have available includes: • These notes • Various lab manuals. • The Unix on-line manual system, described below. • Vast amounts on-line on The World Wide Web. Meanwhile, these sessions are about Unix and it is appropriate that you should start to un- derstand the Unix manual system. Most Unix commands are described in the on-line manual system, which you use by typing: man  e.g. man fortune  tells you how to use fortune, and man man  tells you how to use man itself. When you have time later, look at this manual and find out what the -k option does. You will find this information very useful – how are you going to make sure you don’t forget to have a look at it later? An example man page to try right now is man xclock  This tells you how to create a variety of clocks on your screen. Look particularly at the section headed SYNOPSIS, which tells you what options are available, and the one headed OPTIONS, which tells you what they do. If the description takes more than a page of your screen, you will see a colon at the bottom : When this occurs, you can see the next page by pressing the space bar. To move down the text only one line at a time, press  . To quit reading the manual page, type q.

1.14 Command line arguments, interrupt and background running There’s one problem with running clocks from an xterm. If you type: xclock  a clock does indeed appear. However, you then can’t type any more commands in the xterm window, because it is waiting for the clock program to finish, and of course the clock program is designed to run forever (or at least until you logout). There are several ways to get round this: • When you’re bored with a clock, you can delete it by choosing the Delete option from the Window Operations sub-menu. The clock will disappear, and you’ll get a prompt back in the xterm window. • You can obtain the same effect by typing c (hold the ‘Ctrl’ key down and type c at the same time) in the xterm window where you typed xclock. This is worth remembering, since you can use it when your own programs accidentally run forever! 21 Introductory Unix Labs

• If you type an ampersand on the end of a command, e.g. xclock &  , the program gets run in the background, that is, separately from the xterm window. This way you can have several clocks at once and continue typing other commands in the xterm window. Try all of these three approaches. Work out from the manual how to use the various options of xclock, and experiment with producing a range of clocks. (You should ignore the section of the manual page entitled X DEFAULTS – for now.) Work out the command line arguments needed to make a clock have red hands with blue edges. If you have time later, try to figure out how to make a clock have a yellow background – hint: there is only a good clue in the xclock man page, you will need to look at another man page to get the answer.

1.15 Locking the screen Whenever you leave your computer unattended, you should lock the screen so that no-one can damage your files (or worse). The simplest way to do this is click on the Lock Screen option of the main menu. The Select xlock mode option gives you a form offering the choice of some 100 or so different modes (on 3 pages) for a program called xlock. Try it – select one of the modes and click on the Try button. Don’t move your mouse, because any mouse movement will end the trial. Try a few modes, ending each trial by simply moving the mouse. Now select one of them and click on Lock Screen. You have locked your screen, so you could in theory go away as your login session is protected. But we have a rule in our School laboratory policy: you must never lock your screen for more then 20 minutes. That’s ample time enough for a toilet break, or to stretch your legs – something you are recommended to do every hour for health and safety reasons. If you are going to be away for more than 20 minutes, you must log out instead: it is very anti-social indeed to hog a machine you are not actually using, and we take a very dim view of it. (Anyone who offends repeatedly in this way, has their account set so it can only be used between 5pm and 9pm!) Now, with the screen still locked, type  . Notice that xlock shows your user-name and the time which has elapsed since you locked the screen. Whenever and however you lock your screen your user-name and the elapsed time must always be shown. This is because if the elapsed time is more than 20 minutes, anyone wanting to use the machine has a right to log you out (by killing the X server) and then log in. The user-name is needed so that a member of staff can tell whether or not you are supposed to be present in a laboratory which may be happening at the time. If either the user-name or the elapsed time is missing, you are breaking the rules and anyone is allowed to assume you are not supposed to be there and/or that you have had the screen locked for more than 20 minutes! Now unlock the screen: type  to get xlock’s attention, then type your password. You should now be unlocked, but if it didn’t work, just try it again – perhaps you mis-typed your password. Session 1: Introducing Unix 22

1.16 Preferences menu You will recall we earlier brushed over the Preferences sub-menu. This sub-menu enables you to change much of the FVWM set up you are using. The preferences are split into items as follows: • All Menu Button Panels – this enables you to control which menus have their button panels on the right of the screen. It is probably a good idea to leave all 6 enabled for now, and decide which ones you want to keep after you have become more familiar with them. They can be extremely convenient, once you have learnt which buttons do what. These button panels can each also be toggled on and off from the top of the cor- responding menu (e.g. you can see the sub-menu item for controlling the Preferences button panels at the top of the Preferences menu. • Stored Preferences / Themes – this menu allows you to load, save and delete your own sets of preferences, load ready made themes and specify which preferences and/or themes you would like to be chosen randomly each time you log in. For convenience, this menu can also be obtained by clicking at the very top of the main menu. • Initial Windows – this pops up a form which enables you to control the windows that are started when you log in. • Web Browser Choice – this pops up a form which enables you to choose your default web browser from a list of known ones. • Editor Choice – this pops up a form which enables you to choose your default text editor from a list of known editors. • Look () settings – this menu enables you to choose various settings which affect the way your screen looks, such as background image and the colours of menus. • Feel settings – this menu enables you to choose various settings which affect the way your user interface feels, such as the speed of the mouse and whether or not you want animations.

1.16.1 Choosing a background colour The option Preferences -> Look (theme) settings -> Screen Background -> Static enables you to control the colour of your background. (I.e. the Preferences option on the main menu, following through to the Look (theme) settings sub-option, etc..) You are going to use this right now to pick a solid background colour. Select that menu item, and a form will pop up. This has 3 sliders corresponding to the colours Red, Green and Blue – the RGB system used in computer colour generation. By moving the sliders about, you can change the colour inside the little square on the screen. Position the pointer on the knob of the top (Red) slider, press (and hold) the left mouse button, and move the slider rightwards until it is at position 145. Now do the same with the middle (Green) and bottom (Blue) sliders. You now have a grey colour because all three sliders have the same value. If you were to move all three sliders together to the left, the shade would get darker, and to the right, the shade would get lighter. If all 3 are on zero, you get black, and when all 3 are on 255, you get white. Now move the top slider to 255. If you’ve got the other two still at 145, you’ll have a nice retro pink colour. See how the colour is described, under the little colour box, as a string of 6 hexadecimal (that’s base 16) digits, 2 digits for each of the 3 sliders. Experiment with other colours: try ‘#B89163’ if you’re feeling muddy or ‘#B891FF’ if you want a ‘mind-expanding experience’ (JTL used to have a shirt that colour ...). 23 Introductory Unix Labs

Now click on the button labelled Auto Frame? This enables you to select the colour of your window frames. By default, it chooses a colour which is similar to the background colour; sometimes a bit lighter, sometimes a bit darker. See how the bit of picture which looks like a window frame changes its colour when you move one of the sliders. Instead of having a different shade of the same colour as the background, you can set a related colour for your window frames. This is done in a sneaky way by simply negating one, two or all three of the settings for the colours Red, Green or Blue. When all three negation buttons are selected (that is, they have a little x in them) your window frame choice will be the opposite of your background colour: nice if you want to make a striking impact on those around you who have a hangover! Try various combinations of the three negation buttons. The Step button is a handy way to step through all 8 possible combinations of these three buttons: try clicking it all eight times. (See, you even learn about binary counting when choosing your window frame colour!) You might like to try choosing a Picture instead of a colour, or a mixture between your Uniform colour and your frame colour, but don’t bother just yet – you can fiddle around later. For now, choose a nice background colour and matching frame colour, and click on the OK button: this applies the colour, remembers it for the future, exits the window, and probably does a restart (if your window frame colour has changed). The restart can take a few minutes: just be patient.

1.16.2 Other preferences There are many other preferences you can set, such as a moving background, less buttons on your window title bars, the colours inside your xterms (and nedit to match), the colours of your menus, your choice of editor (if you don’t like nedit – try it first), and so on. You can even store different sets of preferences to be recalled whenever you like depending on your mood. There’s also currently about 60 Shared Themes you can load, which are each sets of matching preferences previously prepared for you.

1.17 The other window title bar buttons So far we have explored 4 of the 8 buttons on window title bars. The remaining 4 are: • The button second from the left toggles the sticky window feature. See how the title bar gets some lines along it when the feature is on. To see what it does, put the feature on for one window (e.g. xterm) and then change to another page of your desktop (you remember how to do that, don’t you?). Now go back to the first page. Try taking it to your other desktop. • The button third from the left is the window shade feature. Press it on a window. Press it again. The effect is like rolling the window up into its title bar, and then down again. Hence the name: shade, as in the US English for roller blind. • The buttons fifth and fourth from the right are the wide maximise and tall maximise buttons, and they make the window stretch to full width and full height respectively. Note that if you press one of wide maximise, tall maximise or maximise (the right- most button) and then press any other of them, the window will be restored to its original size, rather than what you think it might do. (That curious feature will change in AnotherLevelUp when FVWM2.6 comes out.) Session 1: Introducing Unix 24

You can select which of these eight buttons you want (for a particular set of stored preferences) by selecting Preferences -> Look (theme) settings -> Window Buttons from the main menu, and looking at the bottom of the form which then appears. However it’s a good idea to keep all 8 for now until you become sure which ones you like to use – they are all useful, even the ones that do not exist on Windows. For example, why full screen a window when more often you only want to tall maximise it? Speaking of which, try holding the ‘windows’ key at the left of the keyboard and typing t. And again. Do that with w and again with f. Please get out of the habit of full screening a window, when really you only want it to be taller, or wider.

1.18 Stored preferences Okay, maybe now it’s time to have a short play at changing your screen preferences and so on. To get a good idea of what’s possible, you should try loading one or more of the ready- made shared themes. Select Preferences -> Stored Preferences/Themes -> Load shared theme -> Load Blue Water (i.e. the Preferences option on the main menu, following through to the Stored Preferences sub-option, etc.). Because you earlier changed the background colour, you will be asked whether you want to save your current preferences. It’s entirely up to you – are you proud of your previous choice?! The new files will be loaded and FVWM will restart. Again, be patient: it takes a few minutes. Doing this will have changed the colours of your xterms and nedit, but only for new ones, not those already existing. So when everything has settled down again, you should close all the windows (xterm, nedit, Firefox and Thunderbird) you have; and then select Exit Fvwm -> Other Options -> Restart Programs. This is a bit like logging in again, in the sense that all the things which are started when you log in are started again now.

1.18.1 Making your own theme Try more shared themes (you can preview them from Preferences -> Stored Preferences/Themes -> Load Shared Theme -> Web Preview of themes), and then try making your own set of prefer- ences. If you want to use a picture as a background, it’s best to select that first, via Preferences -> Look (theme) settings -> Screen Background -> Static. On that form there is a picture browser. You can of course use your own picture, perhaps downloaded from the web; but make sure it does not cause any offence to anyone – please. Once you have chosen your picture, you can select a uniform background colour and frame colour to suit it. Do this even though you might think you won’t need the uniform background colour: you’ll soon figure out why. A feature planned for the near future will enable you to export your preferences to other users, so they can use them.

1.19 ARCADE Client Before you finish this (long!) first session, we would like you to register your access to the ARCADE server. ARCADE is the laboratory management system we use to administer course- work marks and deadlines, etc.. You can use the client query program to look up your details, 25 Introductory Unix Labs

laboratory timetables, marks, and so on, throughout the year. It is recommended you do this fairly regularly, if only to check that mistakes have not been made in your marks! You need to register with ARCADE before any of your lab work can be marked, so it is much better to do it now than wait until your first deadline! On the main menu, find the sub-menu called ARCADE and select the ARCADE Query menu item. After a short pause, a new window will pop up. In the large text box you should find a message telling you that you are not yet authenticated, and that you have just been sent an email. If this is so, then quit the program, read the email you have just been sent by the ARCADE server, and carefully follow the instructions in it. Then you will start the ARCADE Query client again, and it should now connect you to the server. If this works, then your access is set up! Here’s a question for you: can you think about how that worked? Something has just happened so that now whenever you run the client, you can access your details, but no-one else’s. And others cannot access yours. Explore the various queries of the client, and familiarise yourself with the user interface. Check that your registration details are correct. Feel free to ask for explanation if it is not obvious to you.

1.20 Really finished Session 1? If you finish early it is better to practise manipulating the windows than to go onto the next exercise. The more familiar you are with the user interface the more time you will save, and the less costly mistakes you will make later. Try out the menu options we didn’t look at. Explore the relationship between the main menu options Other Programs and Shell browser and Favourites. Find the Open Office items on the Other Programs menu and try them out. These are ‘open source’ (free) versions of the well known Microsoft Office Tools. If you’ve taken less than an hour, grab a piece of paper, and a pen, and make a brief list of all the things you’ve just learnt. Then scan the text and check what you missed from your list. If you score less than 90%, go back to the start and do it all again! When you’ve finished, you must log out – otherwise the hackers will be able to impersonate you, and life will be miserable! Log out by choosing the Yes, Really Quit option of the Exit Fvwm sub-menu available at the bottom of the . Don’t forget to tell the laboratory supervisor that you have completed session 1. If you do not finish during the session, that is okay, but please tell the laboratory supervisor during session 2 that you have completed session 1.

1.21 How will you remember what you have just learnt? E.g. how do you run a command in the background? How can you make a window go to the bottom? Why don’t you flick back through this section and make a list of everything, so you’ll remember it? Session 1: Introducing Unix 26 Session 2: Manipulating files and directories

This session concerns the practical aspects of manipulating files and directory structures. It is extremely important that you work through it carefully, in sequence, and complete everything (except possibly some of the Exercises at the end). The second section contains some notation which you need to understand before you start.

2.1 What is a file? A file contains information, which may be in human-readable text form, or in other forms, e.g. • An object program; this contains machine instructions. • Data held in some format known to the programs which use it, but not readable by humans, for example, a database. • Compressed or encoded data, e.g. some files containing accounting information about usage of the system. • A directory. This is a file which contains information about other files, and gener- ally can be regarded as something which contains other directories and/or files. (In Windows these are called folders.) Although most of the files you will work with contain text, you will soon learn (if you do not know already) that all computer information is represented as binary digits (or bits). In the case of a text file, the bits are interpreted as characters. In the case of an object program, the bits are interpreted as machine instructions. In the case of a file of some other sort of items - let’s call them widgets – the bits are interpreted as widgets.

2.2 Specifying filenames in Unix In Unix, as in Windows, the files and directories you create can have more or less any name you like. It is very sensible to give them names which mean something and make their purpose clear. This is despite some of the traditional file names in Unix being rather cryptic – this is particularly true for some of the commands (which are themselves object files). You’ll get used to that. On each machine, there is one directory called the root which is not contained in another direc- tory. All other files and directories are contained in root, either directly or indirectly. The root directory is written “/”. Note this is the opposite slanting slash character to that used by MS- DOS and Windows. When Microsoft borrowed the idea of directories from Unix they chose the other slash to distinguish the two systems. (Those of you with Microsoft experience should also compare the principle of one root per machine with the Microsoft principle of a ‘root’ per disk on each machine (e.g. A:, C:, etc..)).

Introductory Unix Labs Session 2: Manipulating files and directories 28

If we wish to talk about the file y within the directory, x we write x/y. y may itself be a directory, and may contain the file z, which we can describe as x/y/z. You can think of this structure as defining a tree, with “/” as the root (hence its name), direc- tories as branches, and other files as leaves. You will study trees as an abstract structure, later in the year. This simplified model of the Unix file system structure will do for now. (For those of you who are interested: Unix actually allows links, which means the structure can really be a cyclic graph. Links are similar to, but fundamentally not the same thing as, shortcuts in Windows.) Apart from “/”, there are two more directories of special note: • Your home directory is the directory where you find yourself when you log in; this will be some way ‘down the tree’. For example, mXXXXXXX’s home directory is /home/mXXXXXXX – in other words, the directory mXXXXXXX within the directory home within the root directory. • Your current working directory is the one you are working in at a particular moment. For example, a student mXXXXXXX who is working on INTRO, exercise 2, should have the directory /home/mXXXXXXX/INTRO/ex2 as current working directory. (You will create this directory shortly.) A name which uniquely identifies a file (on a given machine) is called its pathname because you are specifying a path through the tree to reach it. Pathnames can be given in two ways: A pathname beginning with a “/” is an absolute pathname, which starts from the top of the tree, e.g. /home/mXXXXXXX/INTRO/lightbulbs A pathname without the initial “/” is a relative pathname, relative to the current working directory. For example, if the current working directory is: /home/mXXXXXXX/INTRO the same file can just be called lightbulbs while from /home it can be referred to as mXXXXXXX/INTRO/lightbulbs It is important to realise that, unlike Windows, Unix filenames are case sensitive, so that the file name myfile is completely different from, and has no relationship to, the filename MyFile. Historically most Unix file names have tended to be all lower-case but this is not a rule. Quick exercise: This method of specifying relative pathnames has a severe limitation. Think about what it is, and how it might be overcome. (Solution later – if you spot it.) Log on and go into X with AnotherLevelUp Fvwm95, then follow the instructions in the next sections.

2.3 The pwd and ls commands The pwd (short for “print working directory”) command prints the absolute pathname of your current working directory. In an xterm window, type pwd  and it will show you the name of your home directory. The ls (short for “list files”!) command shows the files in your working directory. If you type 29 Introductory Unix Labs

ls  you’ll see something like: My Music SeaMonkey-Win desktop.ini folders pine-nt This doesn’t actually show all your files, some are hidden by the normal ls on the assumption that you don’t want to see them most of the time. The names of these hidden files all start with a dot. If you try ls -a  you’ll see something like: . .ab_library .mailtool-init .xserverrc .. .bash_logout .openwin-init.olvwm My Music .OWdefaults .bash_profile .openwin-init. SeaMonkey-Win .Xauthority .bashrc .openwin-menu desktop.ini .Xclients .cs_maildir .openwin_solaris-start folders .Xdefaults .dtprofile .openwin_sunos-start pine-nt .Xmodmap.sun4 .emacs .textswrc .Xmodmap.sun5 .fvwm2rc.m4 .twmrc .Xresource .mailrc .xinitrc -a is an option on the ls command (short for “all”). Options which are either there, or not, are also called flags. Various files, most of which have names beginning with a dot, were created for you when your account was set up. The purpose of some of these ‘dotfiles’ will be explained properly later. Most of them are used to provide information needed by commonly used programs. For instance, the file .xinitrc controls the mechanism followed when starting up X in one of the several machine/software environments available in the school. The directory called .mozilla contains your personal setup and various other files for use by Mozilla. Now try the -l flag of ls ls -l and then both -a and -l flags ls -la The -l flag gives lots more information about the files shown, rather than controls which files are shown. This information includes the date of last modification of the files, the owner of the files, and other things you don’t need to worry about just this minute (see Exercises later on).

2.4 Creating a directory structure You’re now going to use the mkdir (“make directory”) command to create some directories. Type mkdir INTRO  Check that this directory has indeed appeared using ls. It’s important that directories we ask you to make for your work have exactly the names we specify. Unix will let you use any names you like, but we have to impose conventions for administrative reasons. If you made a mistake, e.g. intro instead of INTRO, you can remove the directory while it is still empty with the rmdir command: e.g. rmdir intro  Session 2: Manipulating files and directories 30

And then try to make it correctly. The cd (“change directory”) command allows you to move around the tree by changing your current working directory. Type cd INTRO  to make INTRO your working directory. Check that you have changed current directory (if you can’t remember how – slow down!). Note that the version of cd that you are using also does something similar to pwd. Now make directories for each of the INTRO exercises mkdir ex1 ex2 ex3  The cd command on its own takes you back to your home directory, wherever you may be when you invoke it. Try this out by typing cd  Check that you are now in your home directory. Your directory structure should now look something like this your home directory

INTRO

ex1ex2 ex3 The easiest way to check this is to use (from your home directory) ls with the -R flag. This shows the whole tree below your current working directory (-R is short for “recursively” – look up the word in a dictionary, or wait until later for a definition! ). ls -R  Now you should make a directory for the COMP16121 course unit with sub-directories for each of the 10 exercises associated with that course. You must use the same convention as above: capital “COMP16121” and lower case “ex1”, etc.. You must get your directory structure right before continuing – ask a member of the lab staff to check it at this point.

2.5 The ‘dotfiles’ (and shell variables) Every directory is created with two files already there, called “.” and “..”. Of course, you don’t see them when you run ls because they start with a dot! Now run the command which will enable you to see them in your current directory. “.” is a reference to the directory itself, and “..”is a reference to the directory above it in the tree. This may seem rather bizarre at first, but they are in fact extremely useful. “..”, for example, enables you to specify a relative pathname up the tree. 31 Introductory Unix Labs

Try the following sequence of cds, checking where you are after each one, and make sure you understand what is going on! cd  cd INTRO/ex1  cd ..  cd ex2  cd ../ex1  cd ../../INTRO/ex2  cd ../..  As we said earlier, the other dotfiles in your home directory contain assorted useful information. For instance, the file .bash_profile sets all manner of things each time you log on – you should take a look at it some time, but not just now. Among the many things it does, it sets the value of a shell variable called $INTRO to the long and boring path name of the place where we keep the master copies of various files used in INTRO. Let’s look at its value – type echo $INTRO echo is a command which just displays its arguments – very useful just here. If shell variables didn’t exist, or if we hadn’t taken the trouble to define $INTRO (etc.) for you, you’d have to remember and type long path names like that one frequently – starting in the next section! There is another shell variable which is set for you, called $HOME. Find out its value. Now you can easily reference your home directory from wherever you are. Actually the shell you are using (what is it called?) provides you with an even more convenient way of referring to your home directory: you can simply use a single tilde character. ls ~

2.6 Copying, moving, and removing files This section introduces three commands used for copying, moving and removing files. We first describe each command and then invite you to practice using them. The cp (copy) command has two forms. The first general form is cp  For example cp file1 file2  makes a copy of the file file1 and calls it file2. If a file called file2 already exists, you will be warned and given a chance to change your mind, or have the existing file2 overwritten with a copy of file1. The second form is slightly different: cp For example cp file1 file2 file3 dirname  This copies the files file1, file2, file3 into the directory dirname, again overwriting any files already there with the same names. The command rm (remove) is used to delete files. rm Session 2: Manipulating files and directories 32

throws away the specified files – always take great care when using rm, it is not reversible, although you will be asked to confirm each remove. The mv (move) command is similar to cp, but it just moves the files rather than makes copies. Again we have the two forms mv  and mv  The effect is like a copying followed by removing the sources of the copy, except it is more efficient than that (most of the time). For example mv file1 file2  is like doing cp file1 file2  rm file1 and mv file1 file2 file3 dirname  is like doing cp file1 file2 file3 dirname  rm file1 file2 file3 Before continuing, answer this question and check your answer with a member of staff: how do you rename a file in Unix? Don’t guess – you know the answer, unless you are going too fast. Now for some practice. Go to your home directory cd  and copy the file called lightbulbs in the $INTRO directory to your current working directory: cp $INTRO/lightbulbs .  Note that $INTRO must be in uppercase and the full stop is essential. If you now do an ls, you should see that the file called lightbulbs has appeared in your directory: ls  If no file called lightbulbs has appeared, the following will probably provide an explanation. If it did appear, read this anyway, just to check that you understand what you did right! The cp command needs two arguments. In this case, the file you are copying is $INTRO/lightbulbs, and the directory you are copying it to is “.” (that is, your current working directory – remember every directory has a reference to itself within it, called ‘.’?). If you missed out the dot, or mis- spelt $INTRO/lightbulbs, or missed out one of the spaces, it won’t have worked. In particular, you may well have got a ‘friendly’, helpful error message like: cp: missing destination file Try ‘cp --help’ for more information. or cp: /opt/info/courses/INTRO/lightblurbs: No such file or directory or cp: INTRO/lightbulbs: No such file or directory 33 Introductory Unix Labs

If you get the first message, it means you used the command with the wrong number of argu- ments, and nothing will have happened. The others are examples of what you might see if you mistype the first argument. If you do get an error message you need to give the command again, correctly, to copy the lightbulbs file across. So you now have a copy of the file, but, it’s in your home directory. You’ll have to get into the habit of not having all your files in your home directory, otherwise you will quickly have an enormous list that will take you ages to find anything in. The use of subdirectories provides a solution to this problem, which is why you created some earlier. Moving this file to the ‘correct’ place gives you a chance to practice the mv command. Move the file lightbulbs to your INTRO/ex2 directory. Notice that INTRO is your INTRO directory, while $INTRO is (an abbreviation for) our INTRO directory, from which you can read things but cannot write to. Now go to your INTRO/ex2 directory and check that the file has arrived there. To make sure you understand cp, mv, and rm, go through the following sequence (in your IN- TRO/ex2 directory), checking the result by looking at the output from ls at each stage cp lightbulbs bulb1  ls  cp lightbulbs bulb2  ls  mv bulb1 bulb3  ls  cp bulb3 bulb4  ls  rm bulb2  ls  rm bulb1  ls  Why does rm bulb1 behave differently to rm bulb2?

2.7 Looking at the contents of files So far, we have manipulated files without caring about their contents. In practice, we often want to look at (and maybe modify) the contents of a file. There are a number of ways to do this. The most general method is to use a text editor, which is the subject of the next session. A quick and easy way to look at the contents of a file is by using the more command. Type more lightbulbs  to look at the contents of the file called lightbulbs (don’t waste your time actually reading all of it!) To go to the next screen full, press the space bar. To move down a line at a time, press  . To exit from more before you reach the end, just type q. more is so named because it prompts for you to tell it to show you “more” of the file when the screen is full. There is a similar command called less, an improved version of more, which allows you to move backward as well as forward through the file – using the arrow keys. Try it. You have to type q to leave less, even when you get to the end of the file. If you want to find out more about less, you can always try man less  Session 2: Manipulating files and directories 34

Try it anyway. Notice how man uses less to display manual pages. This is typical of the Unix philosophy – once a tool is available, it is used in building other tools. Note: you may be used to using notepad, wordpad or word in Windows just to look at the contents of text files, even though these are editors rather than viewers. This would translate into using your Linux text editor (nedit) to look at files, even when you do not wish to edit them. If in a few weeks time your natural instinct is to use nedit rather than less to just look at a file, then you are missing part of the point of using Linux to help you think differently.

2.8 Wild cards An asterisk in a filename is a wild card which matches any sequence of zero or more characters, so for instance, if you were to type (don’t actually do it!) rm *fred*  then all files in the current directory whose names contain the string “fred” would be removed. Try the effect of ls bulb*  and ls *bulb*  Now try echo *bulb*  Are you surprised by the result? One exception to the above rule is provided by the dotfiles; i.e. those whose names begin with “.”. The asterisk will not match a “.” at the start of a file name. To see what this means try the following cd  ls **  and ls .*xinit*  and see the different output.

2.9 Quotas The command quota  shows you what your file store quota is, and how much of it you are actually using. This is only of academic interest now, but may become very important later in the year! You may find that you are unable to save files, or even receive mail, if you use more than your quota of file store. It is important that, if this happens, you do something about it immediately. 35 Introductory Unix Labs

2.10 Putting commands together Before you forget that you’re in your home directory, change directory back to your INTRO/ex2. One of the simplest (and most useful) of Unix commands is cat. This command has many uses, one of which is to concatenate a list of files given as arguments and display their contents on the screen. For example cat file1 file2 file3  would display the contents of the three files file1, file2 and file3. The output from cat goes to what is known as the standard output (in this case the screen). If you type cat  nothing will happen because you haven’t given a file to cat. When run like this, it takes its data from the standard input, which in this case is the keyboard, and copies it to the standard output. Anything that you now type will be taken as input by cat, and will be output once each line of the input is complete. In Unix, end of input is signalled by d. (Recall that typing d in your login shell will log you out – you have told the shell to expect no more input.) So, after typing cat above, if you type (we will omit the  ’s from now on, we hope you’ve got the message) This is some text for cat to digest d you will see the input replicated on the output (interleaved line by line with the input). The first copy is the echo of what you typed as you typed it, the second copy is output from cat. This may not seem very useful, and you wouldn’t actually use it just like that, but it illustrates the point that cat takes its input and copies it to its output. Using this basic idea we can do various things to change where the input comes from and where the output goes. cat > fred1 will cause the standard output to be directed to the file fred1 in the working directory (the input still comes from the keyboard and will need a d to terminate it. Try creating a file fred1 using this technique, and then check its contents. cat < fred1 will take the standard input from the file fred1 in the working directory and make it appear on the screen. This has exactly the same effect as cat fred1 You can, of course, use < and > together, as in cat < fred1 > fred2 which will copy the contents of the first file to the second. Try this and check the results. We can, of course, do this type of redirection with other commands. For example, if we want to save the result of listing a directory’s contents into a file we just type something like ls -l > fred1 (this overwrites the previous contents of fred1 without warning, so be careful of this kind of use). One of the other things that cat can do is to put line numbers on its output. It does this if you use the -n flag. Try Session 2: Manipulating files and directories 36

cat -n fred1 Now suppose, for the sake of argument, we wanted to have a listing of the names of the files in the current directory, with each line numbered, and the result saved in a file fred3. You have just been given all the information you need to do this – so, how would you do it? Do it now. Unless you’ve met Unix before, you probably did something like this ls > tmpfile cat -n tmpfile > fred3 Or if you didn’t then try it now and examine the contents of fred3. The file tmpfile can now be thrown away using rm tmpfile. It’s a shame we had to use an extra, temporary, file. Could we avoid having to? Why do you think the following would not work? ls > fred3 cat -n fred3 > fred3 A better way of doing the task, which avoids the use of a temporary file is by use of a powerful Unix feature called the pipe. We just type ls | cat -n > fred3 The pipe symbol | indicates that the standard output of the first command is to be piped into the standard input of the second command, so no intermediate file is needed. We can construct another (slightly artificial) pipeline example using just cat. cat < fred1 | cat > fred2 The first cat takes its input from fred1 and sends its output into the pipe. The second cat takes its input from the pipe (i.e. the output from the first cat) and sends its output to fred2. (How many other ways can you think of to do this?) This isn’t a frightfully sensible thing to do, but it does illustrate the principle of piping (long pipelines of commands may be constructed), and more realistic examples will appear in the exercises. Standard output sent to the screen may come so fast that it disappears off the top before you have had a chance to read it. There are three ways around this problem. • Using foresight, pipe the output into the command more or less which arranges to stop after each page full. For example, ls -la | less

would be a wise precaution if the current working directory held more than a screen full of entries. When less has shown you the first screen full, press to see the next screen full, or  to see just the next line. • Without foresight, the output will rush past you at a great rate of knots. Press s to stop it dead in its tracks (and q to set it off again). In practice this isn’t much use nowadays – in most cases the computer is just too fast for the Human to press the keys at the right time.

2.11 Printing text files The command lpr can be used to send files to a printer. In its simplest form, you simply run: lpr file1 file2 37 Introductory Unix Labs

to print the given files. You could use it now to print out the lightbulbs file, but that file is quite big and we don’t want to waste a lot of paper. So please don’t! However, it would be nice to practice using lpr. So, you shall print out just the first 50 lines of it. Look at the man page for lpr and discover what it does if no file names are given. Now look at the man page for the command head and figure out how to make it output the first 50 lines of the file lightbulbs. Experiment with this to make the 50 lines appear on your screen. From what you have already learnt, you should know how to check there are exactly 50 lines using the counting option of cat. Now send the 50 lines to the printer – without using an temporary file. Go and collect your print output – ask for directions to where the printer is. lpr is a basic printing tool for printing text (and it is also clever enough to print most types of images nowadays). A more sophisticated printing program is a2ps. This produces a nicer output, and is clever enough to recognise different types of text file, including program source code files, and present the various keywords of the programming language and the program identifiers in different fonts to help with readability. Look at the man page for a2ps, figure out howto print the file $INTRO/SimpleJavaProgram.java and then do so. When you collect this print output you will see how pretty a2ps makes it. This is a good way to obtain print outs of your own work, should you wish to.

2.12 Exercises Here are a variety of things to experiment with if you finish everything else. More details of the relevant commands can be found by using man. 1. As stated above, ls -l gives you extra information about files. Skim through the man page for ls to see what it means. Check the ownership and protection of your own files. Why don’t you own “..” in your home directory? For more about ownership and protection, look at the manual pages for the chown and chmod commands. 2. Lookat the man entry for rm and find out what would happen if you did cd and then rm -rf * NB. DON’T TRY IT! We once had a system administrator who, after logging in as the superuser (that’s a special user called root that has the permission to do anything), typed the above command by accident. What do you think happened? (Hint: on many Unix systems, the superuser’s home directory is /). 3. Another useful command is grep, which displays all lines of a file containing a partic- ular string (in fact, the string can be a pattern with wild-cards and various other things in). The form for a simple use of grep is grep This will result in a display of all the lines in the files which contain the given pattern. A useful file to use for experiments with grep is /usr/share/dict/words, which is a spelling dictionary. Try to find all words in the dictionary which contain the string “red”. 4. Use a suitable pipeline to find out how many words in the dictionary contain the string “red” but not the string “fred”. (Hint: The answer to the previous question gives all the words containing “red”, look at the manual page for grep to find out how to exclude those words containing “fred”. The wc (short for “word count”) program counts words (amongst other things). Use pipes to put them all together.) Session 2: Manipulating files and directories 38

5. Investigate the ps command, which tells you about the processes (running programs) on your workstation, how much swap space they are using etc.. 6. (Harder) Wander around the top of the directory tree, from /, and try to understand what you find there. 7. Try the exercises contained in the file $INTRO/extras. Session 3: Text Editing

3.1 Computer text processing This session will introduce you to Nedit, a simple text editor, which you will use a great deal throughout your course (unless you find another editor that suits you better). The techniques you will learn today are fundamental, and you should practice them until you can do them without thinking. This session only covers the basics. For information about other facilities in Nedit, and for quicker ways of doing things, see the Help menu in Nedit.

3.2 Document preparation systems There are many computer programs available which help in the preparation of documents. They can be very roughly classified as follows:- Atexteditor allowsyoutotypetext,correctmistakes,andmodify the text at will. You will use the text editor Nedit to write your computer programs, etc.. Atextprocessor takestext,withextraformattingcommands, and formats it neatly, using a variety of fonts and formatting conventions. These notes are produced using such a system, called LaTeX (pronounced “lay-tek”). Awordprocessor suchasMicrosoftWordisacombinationofatext editor and text processor. A desktop publishing system combines text editing and formatting with many other facilities such as drawing packages, spelling checkers, and automatic main- tenance of references, tables of contents, footnotes and indices. Such systems (and some word processors) are often described as WYSIWYG (What You See Is What You Get) because the docu- ment appears on the screen in (more or less) the form in which it will be printed. In practice the boundaries between these types of program have become increasingly blurred as text processors and word processors incorporate more and more desktop publishing facilities. The remainder of this section is devoted to an introduction to the text editor Nedit. Nedit is only one among many text editors available on Linux; once you are familiar with the principles of text editing you may like to explore others, some of which are described on the local Software Links web page.

Introductory Unix Labs Session 3: Text Editing 40

3.3 Creating a small piece of text Move the mouse pointer into your Nedit window and type: A: Two, one to screw it almost all the way in and the other to give it a surprising twist at the end.

Q: How many mystery writers does it take to screw in a light bulb? (Yes, we know it’s the wrong way round – this is deliberate!) Notice how the blinking vertical line (the cursor) indicates where you are inserting the text. You can move the cursor around in the text by pointing to where you want it and clicking the left mouse button. For short distances, it may be more convenient to use the arrow keys on the right hand side of the keyboard. The Return key inserts a newline at the cursor. Make sure you put newlines in exactly as shown above. The Delete key deletes the character to the right of the cursor. The backarrow above the return key deletes to the left. By moving the cursor, deleting characters, and inserting new ones, you can correct any mistakes you make. (If you haven’t done so already, make some deliberate mistakes and correct them.)

3.4 Selections Many operations in Nedit are done by selecting pieces of text. To make a selection, select the beginning with the left mouse button and then, still holding the left button down, wipe across the desired text. The selected text appears highlighted, with a different background colour. There are quicker ways of making common sorts of selections: • Click the left mouse button twice fairly rapidly to select the word you are pointing at. • Click the left mouse button three times to select the line you are pointing at. • Click the left mouse button four times to select the whole text. Experiment with selecting various bits of the text you have typed. Try each of the methods described above.

3.5 Cut and paste One of the main advantages of computer text processing is the way you can move text around, and change the structure of a document very easily. Most text editors have operations called cut and paste. Cut deletes a piece of text and (invisibly) saves it somewhere. The place where it’s saved is called the clipboard. Paste takes whatever text is currently on the clipboard and inserts it at the cursor. Hence, a cut followed by a paste can be used to move a piece of text from one place to another. Try this on your text: • Select the question part of the light bulb joke. • Select the Edit menu by clicking on Edit with the left mouse button; Select Cut by clicking with the mouse button. The selected text will disappear. • Position the cursor at the beginning of the text, where the question should have been. • Choose Paste from the Edit menu , and the text will reappear in the correct place. 41 Introductory Unix Labs

In what follows the notation: Edit £ Paste means select the Edit menu and choose Paste from it. The Edit £ Copy option allows you to copy some text to the clipboard without deleting it. You can then paste it wherever you want to. Try using this to make an extra copy of the whole text within the Nedit window. An alternative to using two mouse clicks, first on the menu and then the menu item, is to pull down the Edit menu by holding down the left mouse button on Edit, dragging the arrow down to the required option (e.g. Cut) and then releasing the mouse button. The keyboard accelerators for these operations are x cut v paste c copy The menu reminds you of these. Try using these to cut and paste, you should find them much quicker than selecting menu options. A powerful feature of the X-windows system (and many others) is that there is a selection and clipboard, shared between all the windows. This means you can easily move text from one document to another. The method which works with (nearly) all programs is to copy onto the clipboard by selecting with the left mouse button and paste with the middle mouse button. This gives an alternative way of copying and pasting in your Nedit window but is more important between windows. For example, you can insert a fortune into your text as follows: In your Xterm window, type: fortune  Select the text produced using the left mouse button. Now move the pointer over to the Nedit window, position the pointer (not the Nedit cursor) to the point where you want the text to go, and simply click the middle button. There is a good chance you didn’t quite get this right: you must position the pointer to the location you want the text to go, and click only the middle button. If you did get it wrong, type z in the Nedit window to undo it, and try again. Now we’ll explain Undo properly! If you cut something you didn’t mean to, Edit £ Undo will restore it for you. In fact Edit £ Undo will undo the last thing you did, whatever it was. z is just a short cut for Edit £ Undo. It is possible to tear off a menu so that it remains permanently on the screen. Click on Edit then above the dashed line at the top of the menu. The Edit Tear-off menu can now be dragged with the left mouse button in the top bar to a more convenient place on the screen.

3.6 Saving text in files The text you are editing is usually a version of some file. The name of the file is shown in the title bar at the top of the Nedit window. Currently, it says (Untitled), because the text hasn’t been saved to a file. The editor also has a current working directory. This is independent of the current working directory in the xterm windows – it has to be set separately. (This is a good thing – often you might want more than one xterm, and more than one Nedit window, each with different current working directories.) To save your text into a file called lbjoke, pull down the File menu by clicking with the left mouse button on the File button, then select the Save As.. option. This will pop-up a window Session 3: Text Editing 42

and you should add INTRO/ex3/lbjoke to the Save File As: line, and finally click on the OK button. This will save the text in your INTRO/ex3 directory as a file called lbjoke. It will also have changed the current working directory of Nedit to your INTRO/ex3 directory. Look at the top line of the text area, and you will see the full path name of the current file. The Nedit current working directory (for a particular Nedit window) is simply the directory containing the file you are editing. Once the name of the working file has been set, as you have just done, you can choose File £ Save, without selecting a name, when you next want to save the file. You should do this from time to time whenever you are editing a document, since any edits you don’t save will be lost when you log out, or if the machine crashes. Linux is more reliable than Windows, but nothing is perfect, and Murphy’s Law (otherwise known as Sod’s Law) tells us that the one time the machine will crash is 5 minutes before an important deadline... Once you save a file two or more times, Nedit automatically keeps the previous version (pro- vided Make Backup Copy in the Preferences Menu is enabled), adding .bck to the end of the filename. Try making a small change to your text, and saving lbjoke a second time. Then check using ls in an xterm window that you now have two files called lbjoke and lbjoke.bck. (If you cannot see these files, remember that you should be looking in your INTRO/ex3 directory!) Note: when selecting a file to load into Nedit, it is rather too easy to accidentally select the backup copy of the file, instead of the main one. If you think about it, you will see why this is a very bad idea – many new students make this mistake and lose hours of work as a result. So please be careful!

3.7 Loading and including files We will now see how to work with a document which is too large to fit onto the screen. The document we will use is the light bulb jokes file. Copy it by: cp $INTRO/lightbulbs .  You did type that in an xterm window, didn’t you? And you were already in your INTRO/ex3 directory weren’t you? If not, then please sort it out, and don’t leave a copy of the file cluttering up your home directory! If you haven’t already done so, save lbjoke. Now load lightbulbs into the editor by choosing File £ Open, then selecting the appropriate entry in the pop-up window, then selecting OK. The first part of the document will appear in the window. If it doesn’t, ask a demonstrator for help. Now include the contents of the file lbjoke within lightbulbs as follows: • Position the cursor between two of the light bulb jokes. • Choose File £ Include File • Select, in the pop-up box, the file name lbjoke and click OK.

3.8 Scrolling When editing a large document, the Nedit window is only able to display part of the text. Changing the portion of text being displayed (usually described as moving around the text) is controlled by the scroll bar, which is situated on the right hand side of the window. A picture 43 Introductory Unix Labs

of the scroll bar is shown in figure 3.1. The position of the slider within the scroll bar indicates where the text you are currently looking at is in relation to the rest of the text. So, currently, we are at the beginning of the file, and the part we can see is only the tip of the iceberg.

Up one line

Up one screen

Slider Goto region in document - drag

Down one screen

Down one line

Figure 3.1: Scroll bar

We can move around the document by selecting the various components of the scroll bar, as described in figure 3.1. For example, selecting one of the buttons at the top or bottom will scroll up, or down, one line. The slider can be dragged to any part of the document by selecting, and dragging, the middle of the slider. Experiment with moving around the document using the scroll bar and mouse buttons.

3.9 Searching Suppose we want to find something specific. One way is to go to a line of the file with a particular line number; to do this, choose Search £ Goto Line Number and enter the appropriate line number. Now find the 142nd line of the document. More common is to search for a string, i.e. a particular sequence of characters. For example, to look for all the light bulb jokes (LBJ’s) containing the string “Three”: • Position the cursor at the start of the file (searching always starts from the current cursor position) • Choose Search £ Find to display the Find window • In the String to Find: box type Three • Click on the Find button, to find the first occurrence of “Three” • To find further occurrences, use the Find Again menu item (or the keyboard shortcuts: g to search forward or G to search backward). Use this facility to find LBJs about doctors, Carl Sagan, and Manchester postgraduates. (Don’t forget to move the cursor to the start of the file before each search.) Note that the string does not have to be a complete word, for example, try “ists”. Session 3: Text Editing 44

3.9.1 Nedit Keyboard Shortcuts Many of the actions which can be selected from Nedit’s menus can also be invoked by using the keyboard. You have seen a few already. For example, your file can be saved by typing s, rather than selecting the Save option from the File menu.

3.10 Find and replace Often, we want to find a string in order to replace it with something else. Choose Search £ Replace and the replace window will appear. This enables us to do various combinations of Find and Replace operations. Suppose we wished to replace all occurrences of some string, for example to replace light by dark everywhere: • Choose Replace to bring up the Replace Window • Type light where it says String to Find: • Type dark where it says Replace With: • Click on the Replace All button. Of course you can reverse this by replacing all dark with light (actually, this doesn’t neces- sarily get you quite back to the original file – why not?). Practice using the various options in the Replace window. The Regular Expression option is an advanced selection option which you will probably prefer to ignore for today.

3.11 Shell scripts In section 1.7 we saw how we could use the shell to write simple programs via the command line, now we see how we can use files containing such shell scripts. Use nedit to create a file, called greeting, containing a slightly modified version of the lines you typed earlier, namely: echo -n "Who are you? " while read name; do if test "$name" = "$USER"; then echo "Welcome $USER" else echo -n "Who?"; fi done Save this file. Now make the file executable by using chmod to change its file permissions. Just chmod +x greeting Now execute it,by justtypingits name in an xterm. You can find out much more about changing file permissions by looking at the man page for chmod.

3.12 Unix Driving Test This section aims to test some of the skills that you have acquired in these introductory labs. 1. Copy the file $INTRO/test-first into a subdirectory of your INTRO directory called UDT (you will need to create this subdirectory). 2. Answer the questions given in this file and edit your copy to include your answers. 3. Send an email to John, with the subject ‘Unix Driving Test Answers’, attaching the file containing your answers. 45 Introductory Unix Labs

3.13 Finishing This is the end of the introductory Unix labs; if you have finished early, please go back and make sure you understand everything you’ve done. The skills you have been developing during these sessions will be very important to you in the future. Don’t forget to tell the laboratory supervisor you have completed this session.

Acknowledgements This document was originally written by Graham Gough, John Latham, and Ian Watson, with additional material by Pete Jinks, Steve Pettifer and Toby Howard.