© Nathan Haines 2017

Nathan Haines, Beginning Ubuntu for Windows and Mac Users , https://doi.org/10.1007/978-1-4842-3000-8_5

5. Command-Line Tricks and Applications

Nathan Haines

(1)Lake Forest, California, USA

At last we come to the command line! That most powerful and often feared topic of all new Linux users. Fairly or unfairly, the command line has a reputation for being arcane and difficult to use. And it is a half truth: a lot of arcane utilities have stuck around—and indeed, any Unix or Linux guru can perform magic inside a terminal window. But the other half of this truth is that the most common commands are simple and easy to use, and the command line is therefore both powerful and comfortable.

If you’ve gone through the earlier chapters, you’ve seen how comprehensive and easy Ubuntu is with pretty much no command-line usage. For daily use, it’s pretty simple to get by without ever opening a terminal window or editing a configuration file. Yet if you search the Internet or Ask Ubuntu for solutions to common problems, you’ll usually find advice in the form of commands to run on the command line. This seems to conflict with what I just said in the first sentence of this paragraph, but when you understand how the command line works, it makes perfect sense.

When specific actions need to be performed in a precise way, it’s very difficult to explain how to perform each step graphically to someone who isn’t familiar with a user interface. On the other hand, with specific commands it is possible to make a computer do precisely what is asked. Giving command-line options virtually guarantees that each step is performed in an exact manner. Unfortunately, this also gives rise to the rumor that Ubuntu or Linux can’t be used without utilizing the command line, and that scares off a lot of users. Fortunately, the simple fact that we’re all the way into Chapter 5 and have already seen tons of practical applications proves that the command line is optional. But for as optional as the command line is for everyday use, it’s not unimportant, either. The command line also functions as a way to get work done even when something goes wrong.

Computers are dumb. They’re fancy calculators that can’t do anything without a list of instructions. And when they operate, they only do what you say, not what you mean. A terminal window is your chance to tell Ubuntu exactly what to do and have Ubuntu do it. In this chapter, we’ll look at some very specific tasks that are best done on the command line. They’re very simple and extremely useful at the same time. And toward the end of the chapter we’ll take a look at less serious tasks and more fun ones. With luck, you’ll find that some of these programs are useful or fun. At the very minimum, you’ll understand why many Ubuntu users prefer to use a command-line interface in certain circumstances. Even if you decide not to use the command line in the future, you’ll at least see that the command line isn’t scary after all.

Introduction to the Command Line

The command line may seem daunting. But the basic commands are very straightforward, and easy to remember. This section will teach you a bit about the command line as well as some basic ways to navigate your way around a terminal interface. I’m not going to attempt to teach you all about the command line! That would be a book in and of itself. But I’ll teach you what you need to know to understand what’s happening in the rest of this chapter. It’s my hope that if you are intrigued by what we do cover together, you’ll pick up a dedicated book on the subject.

Note

The Ubuntu command line is part of a facet of computer history that stretches back to the 1960s, and more directly from the Multics and Unix operating systems. In the earliest days of command-line interfaces, computer mainframes filled half a room and user terminals in the same building were hardwired back to the mainframes. The earliest terminals were teletypewriters. You’d type in your command, which was electronically sent to the mainframe, and the resulting output was sent back to your “teletype machine,” which typed out the results on printed paper, just like a typewriter. These mechanical terminals were eventually replaced by electronic video terminals (sometimes fondly called “glass teletypes”), which were text-only video displays with built-in keyboards. Today, you run a “terminal emulator ” to access the command line. Now you have some context to the brevity of Linux commands and their output. Incidentally, teletype machines and video terminals are still compatible with Linux computers.

Accessing the Command Line

There are two different ways to access a command line interface in Ubuntu, and they function identically. The most common way is simply running “Terminal” from the Dash. This will launch GNOME Terminal in a window. For a more immersive view, you can maximize the terminal window. This gives you all the power of the command line with all the power of the modern graphical desktop, such as anti-aliased fonts and desktop notifications. F11 toggles full-screen mode and is more immersive still.

The other method is to switch to one of your computer’s other virtual consoles . Unbeknownst to you, this entire time you’ve been working on virtual console 7, which displays your graphical interface. As the name implies, there are six other virtual consoles at your disposal. To switch out of the graphical interface and into a text interface, press Ctrl+Alt+F1 to switch to the first virtual console, which is labeled “tty1” (an abbreviation for teletype 1, see the previous note for the historical reference). From here you can use Alt+Left or Alt+Right to switch to the previous or next virtual console, or Alt+Fn, where “Fn” is F1 through F7 to access another virtual console. Note that you need to add Ctrl to the Alt-Fn shortcut when you’re already in the graphical interface but don’t need it when you’re not. This is a fun way to limit yourself to text only if you’re learning to use the command line, but also useful if for some reason your graphical interface isn’t working or freezes and you still want to use your computer. It also mimics what you’ll see if you install Ubuntu server edition on a computer or in a virtual machine . Each console is independent, and any programs you start will keep running no matter which virtual console is active.

If you open a terminal window, you will simply see a command prompt, but if you switch to a virtual terminal, you will see a login prompt instead. It will look like the following:

Ubuntu 16.04.3 LTS ubuntu-book tty1

ubuntu-book login: _

To log in, simply type your username and press Enter. Then you’ll see a password prompt. Enter your password and press Enter. The password prompt won’t give any indication that you’re typing. This is a security feature that prevents others from seeing the length of your password and makes your password more difficult to guess.

The Ubuntu Command Line

Once you have brought up a terminal window or logged in at a virtual console, you will see a command prompt. On Unix and Linux machines, the command-line interface is provided by a “Unix shell” program. In Ubuntu, the default shell is called “bash .” It gives some simple information before prompting you for a command (see Figure 5-1).

A333290_2_En_5_Fig1_HTML.jpg
Figure 5-1. This is your standard Ubuntu terminal window with a bash command prompt

The command prompt displays the current logged-in username, separated from the computer’s hostname, with an @ sign, all in bright green. Because you can connect to other Unix and Linux machines over the network, this is a useful reminder of which computer you are controlling. A colon (:) separates the hostname from the current working directory, which is in bright blue, and finally a dollar sign ($) announces the end of the prompt. Your cursor shows up on the same line after the dollar sign, and your Ubuntu system waits patiently for your command.

You work with the command line by typing a command, and if you need to tell the command anything before it gets started—such as the name of a file—the information it needs is called an “argument.” You separate that from the command with a space before typing it in, and another space after if you are using multiple arguments. When you have typed the entire command, you press Enter to tell the computer to run it. You can also specify options in some cases. These are usually preceded by a hyphen (-). Traditionally, an option with a long name is preceded by two hyphens (--). For example, a command might have -f or --find as synonyms for the same option. Don’t worry too much about these details. They’ll make sense as you work with specific command-line applications.

You can always type the command “clear” and press Enter to erase the terminal window to make the display less cluttered. The shortcut key Ctrl+L also performs the same function. Ubuntu will erase the screen and print your command prompt and any partial command you’ve typed at the top of the screen. You can type “exit” and press Enter to close your Terminal window, or log out of the computer (at a virtual console or remote session) when you are finished. If you close the Terminal window using the red X icon in the title bar, Ubuntu will prompt you if a command is still running.

Working with Files and Directories (Folders)

Moving around the command line is pretty easy to do, and for most simple uses you’ll be looking at files and folders. On the command line, folders are usually called directories . When you first open a terminal window or log in to a computer, you’ll start at your home directory. This is represented as a tilde (∼) in the command prompt. Let’s take a look together at my system. Follow along, and you’ll see different files, but the commands will work the same. My username on the system I used to write this book is “nathan,” so my home directory is “/home/nathan,” although the prompt just says ∼. Note that Ubuntu like all other Unix-like operating systems uses forward slashes (/) to separate each directory, whereas Windows uses backslashes () and Mac OS used to use colons (:), although OS X recognizes both colons and slashes (/) now that it is Unix-based, too. If you want to see what is in my home directory, you can run “ls” to print a directory listing for your current directory:

nathan@ubuntu-book:∼$ ls
Calibre Library  examples.desktop  pratchett.csv
deja-dup         japan             Public
Desktop          keen              Templates
Documents        Music             Time track, 03.09.2014 - 03.15.2014.html
Downloads        Pictures          Videos
nathan@ubuntu-book:∼$

On your screen, files are shown in light gray, but directories are bright blue. Executable commands such as programs or scripts would be bright green. I can view the contents of a different directory in two different ways. I can type a space after “ls” and name the directory, or I can change my current working directory and type “ls” again.

When you first log in or open a terminal window, your working directory is set to your home directory, and commands will typically work with the current working directory and its files, which is why it is prominently displayed in the command prompt. To change to a different directory, use the cd command. Type “cd” then a space, then the directory you want to change to before pressing Enter. Because my home directory contains a directory called Documents, I can just type “cd Documents” and press Enter to change to that directory.

nathan@ubuntu-book:∼$ cd Documents
nathan@ubuntu-book:∼/Documents$

Now the prompt shows my current directory as “∼/Documents,” and ∼ still refers to my own home directory. It helps to keep the command prompt from being too long. Now I can type “ls” again and see a list of files and folders inside my Documents folder.

nathan@ubuntu-book:∼/Documents$ ls
Artificial Heart         Library.tc     Sales Inquiry.odt   Tea.mm
budget.ods               Library.tc∼    sol.exe
demo scale calendar.ics  nanowrimo.odt  Support policy.odt
nathan@ubuntu-book:∼/Documents$

To change back to my home directory, I can either type “cd ..” and press Enter, which will bring me back up one level into the current directory’s “parent” directory, or I can type “cd” by itself and press Enter. If you ask your computer to change the working directory with “cd” but don’t specify a specific directory, it will change the working directory to your home directory . For a list of some other shortcuts, see Table 5-1.

Table 5-1. Short Names for Common Directories

Directory

Shortcut

Meaning

Home

Expands to home directory (example: /home/nathan).

Current

Refers to the current working directory.

Parent

..

Refers to the directory containing the current directory.

Root

/

The root directory contains all other directories.

Running Commands

You can type the name of any command on your system and it will run when you press Enter. Even if you type “firefox” and press Enter, for example, if you are using a Terminal window on your graphical desktop, Firefox will open a new window to display graphics, and you will see any console messages in the terminal window where it is running. (Some “warning” and “info” messages are normal and no cause for alarm.) You will not be able to type new commands until Firefox exits (or at least until you read the later section on multitasking!).

Once a command has finished, bash will print a new command prompt and again patiently wait for your next command. Computers don’t experience boredom, so you should never feel too pressured to take your time or to double-check a command before pressing Enter. Most text commands tend to do exactly what you say without further confirmation and only print feedback if there was some kind of error. This can be confusing if you don’t expect it, but the command line assumes that you mean what you say.

In Ubuntu, most of your commands are in the /usr/bin folder or other standardized locations. When you type a command and hit enter, your system will look through a list of folders one by one for that command and run the first match it finds. This list of folders is called the “system path ,” and it allows you to quickly run commands no matter what directory you’re working. As a security measure, Ubuntu only looks in the system path when you type a command. (Otherwise, a software archive might contain a malicious ls command. You unpack the archive and then type “ls” to see the directory listing, but you’ve accidentally run the malicious program instead!). To run a specific command that is located outside the system path, you’ll need to give the full path to the command. For instance, I have a nice white noise generator command that I saved in a file in my Documents directory called “spacedrive .” To run it, I can type in “/home/nathan/Documents/spacedrive” and press Enter, which will let Ubuntu know exactly where to look. But if I just type “spacedrive” and press Enter, Ubuntu will not find the command and I’ll get an error, even if I’m in my Documents directory, because it isn’t in the system path. Sometimes you’ll want to run a script in the same directory. You can use a period (.) to specify the current directory. So if I’m already in my Documents directory (“cd ∼/Documents”), I can run “./spacedrive” and the script starts right up!

Tip

If you create a directory in your home directory called “bin ,” Ubuntu will add it to your system path the next time you log in. You can put any scripts you write there and run them with just their name. You can run “mkdir ∼/bin” at the command line or use Files to create the directory. The next time we see the spacedrive script in Chapter 6 , it’ll be in ∼/bin.

One last hint is to look at the documentation if you find yourself with questions about how to use a command. There is a lot of help available, and you can usually type “-h” or “--help” after a command to see a summary of command usage and options. You can also read the manual—or “man page”—of a command to get more detailed information. For example, to find out all about the ls command, you can type “ls -help” for a usage summary or type “man ls” and read the comprehensive manual. It explains each option in detail, and is the best way to learn new ways to use commands. The manual is designed to be a reference guide, so you don’t need to memorize every option a command can use. If you want to do something but aren’t sure what the command is called you can search the manuals of commands installed on your system with “apropos” and a keyword related to your intent. For example, “apropos edit” will return a list of man pages with “edit” in the command name or short description. You can scroll through the list (there will be a lot of false positives) and when you find a command that looks interesting, read the man page for that command. It’s a great way to explore and learn right from the command line.

Redirecting Output

Most command-line applications print their output to the terminal as text. One of the most convenient things about using the command line is that you can copy and paste output to save for later. But sometimes you’ll know in advance that you want to save the output of a program to a file, or you’ll want to send the output of one command to another command for processing. This is an iconic feature of Unix that has served Linux very well, and it is one of the nicest things about using the command line.

You can redirect the output of a command to a file by using the greater than (>) sign. For example, if you run “ls ∼ > homefiles.txt”, the shell will take the output from ls and place it in the file “homefiles.txt” in the current folder. You can then open up that file in a text editor, or send it to a friend in an email. You should exercise caution, because using > to save output will replace any existing file with the same name. Using two greater than signs (>>) will create the file if it doesn’t exist, and append (add on to the end) of the file if it does exist.

One way that redirection comes in handy is using the command grep to search and display specific information to save you from having to search or scroll through large amounts of data (we’ll use grep in an example later). You could save the command’s output to a temporary file, but you can use a special character called a pipe (|) to skip that step. When you pipe the output of one command into another program, they both run in parallel, and any output of the first command is treated as input by the second command. You can connect several commands together at one time in this manner, so if you decide to study the command line in the future, you will get a lot of mileage out of this. But for the purposes of this quick introduction, I simply want you to recognize that when you see a pipe, you’re asking the second command to process the results from the first command.

See What’s Running on Your Computer

Computers are great multitaskers . Almost immediately after the boot process begins, they’re doing more than one thing at once. Technically, a single computer processor can only run one instruction at a time (although multicore processors can cheat this a little). But computer time is measured in billions of operations per second and a “multitasking” operating system’s job is to schedule tiny little chunks of programs to run, one after the other. Because this all happens faster than human perception, it appears to us as though computers are doing many different things at the same time. Ubuntu gives you access to the same information about which programs are running that Ubuntu itself has. Since Ubuntu has to keep track of all of your programs, there are a few different ways that you can view this information as well.

The easiest way to see what’s running on your system is to use the ps command . Short for “process status ,” this command will display a list of currently running processes (programs or parts of a program) on your computer. When run with no additional options, this will show any processes that are running as your user and are attached to the current terminal. It looks like this:

nathan@ubuntu-book:∼$ ps
  PID TTY          TIME CMD
2836 pts/12   00:00:00 bash
3111 pts/12   00:00:00 ps

The four columns are simple. PID is the “process ID ” for a line . Every time a process starts, it’s assigned a number. The first process that Linux starts during bootup is the “init” system, which starts (or initializes) every other process, so it’s assigned PID 1, and the PID goes up by one every time a new process is started. You can use the PID to force a process to shut down with the kill command , but it isn’t important otherwise. TTY shows the name of the terminal a process is running on. This was more important in the days when many users connected to a single mainframe, but it is still useful when monitoring a server that many users connect to over the network. TIME shows the cumulative amount of time that the program has used the computer’s processing power instead of waiting on standby. It’s measured in hours:minutes:seconds (if there are four numbers listed, the first one specifies days). The last, CMD, shows the name of the running command.

One of the odd things about ps is that it is actually a very old command, and in various versions of Unix over the years it has displayed different information using different layouts. Because scripts like to run commands like ps and process the output, and many scripts are reused across different operating systems, ps will display Unix-style formatting if it is run with no options or Unix-style options but will mimic the BSD operating system’s ps display if it is run with BSD-style options so that it will be compatible with old scripts. This means that if you want to display all programs that are running as your user by using the “u” option from BSD, the output will look a little different.

nathan@ubuntu-book:∼$ ps u
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
nathan    2836  0.1  0.3  29428  3624 pts/12   Ss   22:59   0:00 bash
nathan    3101  0.0  0.1  25084  1284 pts/12   R+   23:01   0:00 ps u

BSD provides a little more information than traditional Unix does. It displays the percentage of computer processing and memory utilization for each process, the virtual and physical memory being used, the current “state” of the process, the time the process was started, and COMMAND displays not just the command name but also the rest of the command line used to start it as well. The details aren’t important right now, but you should know that sometimes the display will change and it’s nothing to be surprised or worried about. There are a lot of additional options you can use but “ ps aux” displays all processes running by all users on the computer, and this is a good way to see literally everything that’s running on your system. You can use it to see what processes are running and which user they are running under.

While ps will give you a snapshot of the processes running on your computer, a more interesting program called top will show you the processes that are running in real time, updating the list to show which processes are using the most resources.

top - 22:59:43 up 29 min,  3 users,  load average: 1.06, 0.45, 0.29
Tasks: 199 total,   2 running, 197 sleeping,   0 stopped,   0 zombie
%Cpu(s):  9.8 us, 17.3 sy,  0.0 ni, 49.3 id, 18.4 wa,  0.2 hi,  5.0 si,  0.0 st
KiB Mem:   1017500 total,   944564 used,    72936 free,    54172 buffers
KiB Swap:  2095100 total,      412 used,  2094688 free.   422096 cached Mem


  PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
2113 nathan    20   0 1439700  74108  35780 S  33.7  7.3   1:07.87 compiz
1396 root      20   0  344404  54224  14916 S  32.4  5.3   1:01.54 Xorg
2594 root      20   0   44556   2248   1876 S  25.4  0.2   0:35.54 http
2906 root      20   0    4508   1008    640 D  21.8  0.1   0:03.10 updatedb.m+
2008 nathan    20   0  635372  16884  10624 S   9.3  1.7   0:01.95 unity-pane+
2442 nathan    20   0  500820  14720   9004 S   8.6  1.4   0:15.32 update-not+
2536 nathan    20   0  713856  19168  11584 S   5.3  1.9   0:07.33 gnome-term+
    7 root      20   0       0      0      0 R   2.0  0.0   0:03.96 rcu_sched
   49 root      20   0       0      0      0 S   2.0  0.0   0:00.59 kswapd0
1951 nathan    20   0  290292   4048   2824 S   1.3  0.4   0:02.83 ibus-daemon
    3 root      20   0       0      0      0 S   1.0  0.0   0:00.67 ksoftirqd/0
    8 root      20   0       0      0      0 S   1.0  0.0   0:02.70 rcuos/0
2011 nathan    20   0  543420  14196   9444 S   1.0  1.4   0:01.11 ibus-ui-gt+
   11 root      20   0       0      0      0 S   0.7  0.0   0:01.30 rcuos/3
1994 nathan    20   0  816452  17152  10648 S   0.7  1.7   0:01.16 unity-sett+
2051 nathan    20   0  612896  11800   7612 S   0.7  1.2   0:01.66 bamfdaemon
2854 nathan    20   0   31588   1660   1136 R   0.7  0.2   0:00.19 top

This is a lot of information packed into a small amount of space, and every last detail is left as an exercise for the reader (running “man top” will display a very detailed manual). But generally, the top section of the screen shows information about the computer itself and the bottom section shows the running processes under all usernames, sorted from the highest computer utilization to the lowest. This program keeps running until you tell it to stop, and it is interactive. You can use the arrow keys to scroll the display up, down, left, and right, and the PageUp and PageDown keys work as well.

The list of processes updates every three seconds, and you’ll typically use this to find the culprit if a program is causing your computer to run slowly by checking which programs have a high value under the %CPU or %MEM columns. From there you could use the PID of that process to terminate the program, although you should be careful to only terminate programs that you yourself are running or that you know are stuck. Terminating “apt-get” or “dpkg” during a software update could cause major problems. Terminating “firefox” if it’s stuck, however, shouldn’t cause problems. When you are finished using top, you can press the “q” key to cause it to quit and return to the command prompt.

You can terminate a process using its PID by using the “killcommand , followed by a space and the PID. This sends a signal to the process that means “please stop running” and this is similar to clicking the “Close” button on a title bar. A program might finish its current task or ask you if you would like to save before actually closing. But if a program is really stuck, it may not be able to respond. In that case, “kill -9” followed by a space and the PID will cause Ubuntu to forcibly terminate the program. This guarantees results. Why didn’t I give a full command-line example as usual? Because PIDs are different every time, and if you type in an example from a book, there’s no telling what (if anything) might be running with the example PID on your system. So be sure to check carefully before using the kill command!

Multitask on the Command Line

Unix was a multitasking operating system long before interactive graphical user interfaces were common. In order to run multiple programs at once without actually using different terminals, there are a few different ways to stop the current program, ask a program to continue running in the background, and change which program is running in the foreground. Bash, your command shell, handles these requests.

You run a program by typing its name at the command prompt and pressing Enter. We’ll use top as an example because it is easy to see when it is running. If you type “top” and press Enter, it will run in the “foreground,” which means that it is actively using the terminal display and listening for keypresses. But you can stop this program by pressing Ctrl+Z. You will then see the following:

[1]+  Stopped                 top
nathan@ubuntu-book:∼$

This means that the program is no longer in the foreground, and the command prompt means that Ubuntu is waiting for your next command. But the old program is no longer running, either. Instead, Ubuntu has stopped scheduling this program to run on the CPU. It still takes up memory but will not process any information or slow down the computer. You can run other programs, and in fact you can suspend additional programs with Ctrl+Z. They will be stopped as well. For example, if I now run “man top” to read the top manual and want to suspend that temporarily, I can press Ctrl+Z and see the following:

[2]+  Stopped                 man top
nathan@ubuntu-book:∼$

The “2” in brackets means that this is the second job. You can run and suspend as many programs as your computer’s memory will allow. As useful as it is to interrupt a program to do something else, sometimes you want the program to keep running in the background while you work. And eventually you’ll want to call a program back to the foreground. Bash refers to your running programs as “jobs,” and in fact you can use the command jobs to print a list of all jobs whether they are running or not. It looks like this:

[1]-  Stopped                 top
[2]+  Stopped                 man top
nathan@ubuntu-book:∼$

There are two jobs listed, and the “current” job is marked with a plus (+) sign. If we don’t specify a specific job number, any job control command will take effect on the current job. To indicate a job number, put a percent (%) sign before it. To go back to the man page for top so that it’s running in the foreground again, either “fg” or “fg %2” would work. Because job 2 is the current job, specifying its job number to the fg command with “%2” is optional. On the other hand, if I wanted top to continue running in the background, I could run “bg %1”, and top would begin processing again, but I would still be at the command prompt. I could continue working with other programs until I was ready to bring top back to the foreground again by running “fg %1”.

Sometimes you may want to run a program but have it run in the background right away. To do this, simply add an ampersand (&) to the end of the command line before you press Enter. The command will run in the background until you suspend it or until it finishes on its own. So if I want to run ps in the background, I could simply type “ps u &”.

nathan@ubuntu-book:∼$ ps u &
[3] 10410

Bash will print the job number, but instead of printing the command (which you already know because you just typed it!) it prints the PID, so that you can use kill if you need to. Any command you run this way will continue working in the background until you resume control of it with fg or until it stops on its own. When this happens, the next time bash prints a command prompt it will print a message letting you know what happened.

[3]-  Done                    ps u
nathan@ubuntu-book:∼$

If you run this command, you’ll see that ps actually printed to the terminal before it quit. (You may need to press Enter once more to see a command prompt.) Commands running in the background can still print plain text messages. And these commands work with all programs, not just text-based command-line programs. For instance, you can run the graphical benchmark program “glxgears” in a terminal window. A new window will open but every five seconds the program will print graphics performance statistics to the terminal. By pressing Ctrl+Z in the terminal window, you will suspend the job and the graphical output will stop. Typing “bg” will cause the program to work in the background, and the processing will start up again. This makes glxgears a perfect program to test out suspending, backgrounding, and foregrounding jobs.

If you’ve ever wondered how computer users multitasked before graphical interfaces came along, now you have the answer in the Unix and Linux worlds. And being able to suspend and resume programs can be very useful, especially when you’re still getting familiar with the command line and want to reference documentation or check files or running programs.

Diagnose a Connection to a Server

Network connectivity can be one of the most difficult problems to troubleshoot, but two command-line tools can quickly give you information about your network pathway to another computer. Simple to use and understand, one is the first thing that network professionals go to when they can’t connect to a computer, and the other will give you more information about the route your data takes through the network.

The first tool is called ping. This tool sends ICMP ECHO requests to another computer, which will respond to the “echo” request by sending a reply. The ping command listens for these replies and can measure the round-trip delay. Thus, ping is fancifully named after sonar tracking like you see in movies about submarines. Despite the cute name, this is the simplest way to confirm that you have a working network connection to another computer. You run ping by giving it the hostname or IP address of the system you want to connect to. Then, ping sends one echo request every second and listens for the response. It prints a message for every reply it receives. It continues until you press Ctrl+C, which sends a “break” signal to the running program. Then it summarizes the network test results and quits. It looks like this:

nathan@ubuntu-book:∼$ ping www.ubuntu.com
PING www.ubuntu.com (91.189.89.110) 56(84) bytes of data.
64 bytes from www-ubuntu-com.nuno.canonical.com (91.189.89.110): icmp_seq=1 ttl=49 time=156 ms
64 bytes from www-ubuntu-com.nuno.canonical.com (91.189.89.110): icmp_seq=2 ttl=49 time=155 ms
64 bytes from www-ubuntu-com.nuno.canonical.com (91.189.89.110): icmp_seq=3 ttl=49 time=155 ms
64 bytes from www-ubuntu-com.nuno.canonical.com (91.189.89.110): icmp_seq=4 ttl=49 time=155 ms
64 bytes from www-ubuntu-com.nuno.canonical.com (91.189.89.110): icmp_seq=5 ttl=49 time=155 ms
^C
--- www.ubuntu.com ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 4006ms
rtt min/avg/max/mdev = 155.642/155.924/156.546/0.593 ms

For each echo request , it prints the echo size, the reverse domain name and IP address of the target system (many web sites redirect requests to different computers for load balancing, for example), a sequence number, the “time to live” value set on the outgoing request, and the time it took to receive a response. Once it’s finished, it shows the number of echo requests (packets) sent, the number of packets received, and how many packets were lost, as well as statistics for the round-trip time (rtt) measured in milliseconds (ms).

While network troubleshooting is its own book, if you get a response back, you’ll know that data can flow back and forth over the network between the target computer and your computer. This means that no matter what else is or isn’t working, the network itself isn’t to blame. You can use the “icmp_seq” number to see if packets are coming in out of order. If random packets are coming in late, it means that the network route between the two computers is unstable. This isn’t a problem for web pages or downloads, but it is a problem for games and voice or video chat. If the response time is long or varies wildly between packets, or if there are a lot of “lost” packets, this can indicate network path, router, or server problems as well, and sometimes bad network cables.

If you run ping and nothing is displayed, press Ctrl+C after five to ten seconds. If ping displays 100% packet loss then the remote computer is configured to ignore echo requests , there is no network route between you and the remote computer, or the remote computer is offline. While this is not proof that the remote computer is offline, it’s a great way to check for a connection between your computer and your router or your computer and another computer on your same network at home or work.

The other tool that you can use to gather more detailed information about the path between your computer and another is called “mtr” and it works very much like ping, except it traces the route between your computer and the remote system and pings each of those computers as well. You will need to install the “mtr” package via the command line. Type the following command at the command line and then press Enter to install mtr:

sudo apt install mtr

Type your password when prompted, and press Enter. Ubuntu will provide a list of additional software that will be installed along with the software. Simply press Enter at the confirmation prompt to accept the default of “Yes” and Ubuntu will download and install the software.

Once installed, you can run mtr along with a hostname or IP address the same way you ran ping. For example, if I run “mtr -t www.ubuntu.com ”, I see the following display update as new packets are continuously sent:

                             My traceroute  [v0.86]          
ubuntu-book (0.0.0.0)                                  Wed May  3 17:38:04 2017
Keys:  Help   Display mode   Restart statistics   Order of fields   quit
                                       Packets               Pings
Host                                Loss%   Snt   Last   Avg  Best  Wrst StDev
1. 104.236.128.253                   0.0%   100    1.6   0.8   0.3   9.5   1.3
2. 198.199.99.253                    0.0%   100    0.3   1.2   0.3  29.3   4.2
3. sjo-b21-link.telia.net            0.0%   100    2.0   2.2   2.0   5.6   0.4
4. level3-ic-157355-sjo-b21.c.telia  0.0%   100    1.7   6.4   1.6  52.2  11.3
5. ae-234-3610.edge5.london1.Level3  0.0%   100  159.9 160.8 159.8 197.1   5.1
6. ae-234-3610.edge5.london1.Level3  3.0%   100  159.9 160.5 159.8 184.4   3.5
7. SOURCE-MANA.edge5.London1.Level3  0.0%   100  150.1 151.0 149.9 186.1   4.9
8. eth0.lutin.canonical.com          0.0%   100  148.7 148.9 148.6 154.2   0.6
9. www-ubuntu-com.avocado.canonical  0.0%   100  146.7 149.3 145.5 155.1   3.6

This shows me each network router between me and my destination, and it gives me information about the network health of each. The two most important columns are the percentage of lost echo requests (Loss%) and the average response time in milliseconds (Avg). From this I can see if there are any problem points along the way. In this example, I can see that the first four hosts are the path my requests take inside the local network, and the fifth host is where the data hits the Internet and travels to London where the Ubuntu web site is hosted. I can tell that the network is very fast on my local network but slows down considerably on the public Internet. I can also see that host 6 is losing packets, but the other hosts do not appear to be. (This isn’t immediate cause for alarm—in general this happens all the time and computers resend important data if it is not received.) If I were having trouble loading the Ubuntu web site, this would suggest that the web server is fine but data is being lost along the way. But if I was not losing packets and had a low response time (under maybe 400 ms) all the way until the last host which had very high packet loss or response times, that would suggest that the web server itself was the problem. When you are done testing the network pathway, you can press “q” to quit mtr.

Both ping and mtr are both extremely useful tools that are the same ones that network technicians use to help diagnose and troubleshoot network performance on the job, and a full analysis and understanding would take a little bit of study. But even a cursory knowledge of what to look for can verify strong or weak network connections and show you where problems lie.

View Information About the Operating System

There are times when you need specific, detailed information about your computer, and this is another example of where command-line use really excels. On the terminal, you can request certain information, or filter out irrelevant information—all more quickly than you could with a graphical tool.

Determine Your Distribution and Version

Sometimes you have access to a computer, but because you didn’t install the operating system yourself, you aren’t sure exactly what version of Linux is running. You might be able to recognize the distribution by the default wallpaper or the interface, but unfamiliar or heavily modified operating systems will still pose a challenge. One simple command-line tool is common across many different versions of Linux and can help to answer this question.

The Linux Standard Base (LSB) was a software specification created in 2001 to make software development easier across many different Linux distributions. Not all Ubuntu releases are certified as LSB-compliant, but each version of Ubuntu includes an important tool that can help you identify what version of Ubuntu is running. This command is called lsb_release. You can use it to request certain information about the operating system or you can use the option “-a” to display all of the information it will provide. On a standard Ubuntu system, running “lsb_release -a” will display the following output:

nathan@ubuntu-book:∼$ lsb_release -a
No LSB modules are available
Distributor ID: Ubuntu
Description:    Ubuntu 16.04.3 LTS
Release:        16.04
Codename:       xenial

This information is useful in a lot of ways. For instance, the code name is often used when looking for software compatibility. In the displayed result, we see that the code name for Ubuntu 16.04 LTS is “xenial.” You can also ask lsb_release for specific information. For example, if you were running Ubuntu 17.04 and needed to know the release’s code name, you could run “lsb_release -c” and get the following output:

nathan@ubuntu-book:∼$ lsb_release -c
Codename:     zesty

With an easy way to determine the code name for your release of Ubuntu, you don’t have to worry about memorizing it, which can be difficult to keep track of after you’ve upgraded. This is a useful way to narrow down solutions to your specific version of Ubuntu when searching the Web, and is often important to know when working on a server. Because the lsb_release command is available on desktops and servers alike, you might log in to a Linux server and run the command and see the following output:

[root@linux-server ∼]# lsb_release -a
LSB Version:    :core-4.1-amd64:core-4.1-noarch:cxx-4.1-amd64:cxx-4.1-noarch:desktop-4.1-amd64:desktop-4.1-noarch:languages-4.1-amd64:languages-4.1-noarch:printing-4.1-amd64:printing-4.1-noarch
Distributor ID:  CentOS
Description:     CentOS Linux release 7.0.1406 (Core)
Release:         7.0.1406
Codename:        Core

While CentOS is a very popular Red Hat-based server operating system with some significant differences from Ubuntu (particularly how to install software and where network settings are stored), you’ll be able to apply your Ubuntu experience in most cases, and you’ll know what to search for on the Web when investigating any puzzling differences.

Determine Your Architecture and Kernel Version

Sometimes you need to know whether your installed system is 32-bit or 64-bit. This can be useful when downloading third-party software, for example. You might also want to double-check that you have the proper operating system installed, since it isn’t possible to change the operating system without a full reinstallation. Although it’s simple enough to click the gear menu and choose “About This Computer” and read the value given after “OS type,” this works in all versions of Linux regardless of your choice (or lack) of desktop environment.

The command uname stands for “Unix name” and tells you about the operating system kernel that’s running. By itself, it simply tells you the name of the current running operating system, but running “uname -r” will display the kernel version number (the “release”), and “uname -m” will display the machine hardware name. “uname -a” will display all available information, but if you are looking for something specific, it’s easier to read if you only ask for the information you want.

Running “ uname -m” will display “i686” if you’re running the 32-bit version of Ubuntu or “x86_64” if you’re running the 64-bit version of Ubuntu. While 64-bit software requires a 64-bit operating system, the 64-bit version of Ubuntu can also run 32-bit applications. So if your computer supports 64-bit software, you should probably have 64-bit Ubuntu installed.

If your operating system is 32-bit but you want to know if your computer supports 64-bit software, you can read the information in the file “/proc/cpuinfo.” Typing “cat /proc/cpuinfo” will display the contents of the file and all available information about all processors and cores on your system . However, the information we want is in the “flags” list. Processors that support 64-bit wide instructions and memory addresses have a flag called “lm,” for “long mode.” But this can be hard to spot in the alphabet soup of features listed by /proc/cpuinfo. To simplify this, we can use the grep command to search for “lm.” If the processor does not support 64-bit mode, the “lm” flag won’t be listed and nothing will be displayed. If it does support 64-bit mode, then grep will only show the “flags” line and will highlight “lm” in bright red. On my 64-bit computer, running “grep -iw lm /proc/cpuinfo” displays the following:

nathan@ubuntu-book:∼$ grep -iw lm /proc/cpuinfo
flags             : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm 3dnowext 3dnow constant_tsc rep_good nopl nonstop_tsc extd_apicid aperfmperf pni monitor cx16 popcnt lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt arat cpb hw_pstate npt lbrv svm_lock nrip_save pausefilter

This repeats four times because I have a quad-core processor, and grep returns each line that contains a match. It would take some time for you to find “lm” there on the second line, but here it’s highlighted in bright red. If you’re running 32-bit Ubuntu and have a 64-bit processor and at least 2 GB of RAM, you might want to consider installing the 64-bit version of Ubuntu instead. But with these commands you’ll understand your computer and software better.

Add New Users via Command Line

Each user on an Ubuntu system has his own username, password, and home folder. This gives each user a little privacy and the ability to customize the system to his own preferences. And while every user can run the software installed by Ubuntu Software, each application stores its settings in the current user’s home folder. Creating a new user account to allow someone to log in is simple to do from the command line with the adduser command.

Because this modifies the system, you’ll need to start the command with “sudo”. The sudo command is used to run a command with administrative permissions and it will prompt you for your password. By using sudo to run adduser along with the login name of the new user, Ubuntu will create the new account and home folder, and then prompt you for some optional information. The full name is used for Ubuntu’s login screen, but the rest of the information is a holdover from legacy days and can be left blank. For example, if I wanted to create a user account for my friend Alexander, the setup process would look like this:

nathan@ubuntu-book:∼$ sudo adduser alexander
Adding user `alexander' ...
Adding new group `alexander' (1001) ...
Adding new user `alexander' (1001) with group `alexander' ...
Creating home directory `/home/alexander' ...
Copying files from `/etc/skel' ...
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully
Changing the user information for alexander
Enter the new value, or press ENTER for the default
        Full Name []: Alexander Brumley
        Room Number []:
        Work Phone []:
        Home Phone []:
        Other []:
Is the information correct? [Y/n]

Now Alexander can log into my system with the password I’ve created for him. If I want to make sure that he has a unique password that he’ll remember, I can tell Ubuntu to require him to change his password the next time he logs in. This is done with the passwd command’s -e option to set the password as expired. The next time Alexander logs in, he’ll be forced to change his password before he can complete the login process.

nathan@ubuntu-book:∼$ sudo passwd -e alexander
passwd: password expiry information changed.

On a home computer, I might want to allow Alexander to log in by clicking his name without using a password. I can use the passwd command to do this too, by using the -d option to delete the password for that account. This works the same way as before and prints the same status message. Once the password is deleted, the user can log in without a password in the future.

nathan@ubuntu-book:∼$ sudo passwd -d alexander
passwd: password expiry information changed.

When you first install Ubuntu, you create a user account that is given administrative rights to make system-level changes such as installing new software. Accounts you create with adduser, however, are not able to make these changes by default. To allow users to modify the system, you have to add them to the “sudo” user group. The adduser command can add a user to a user group as well. Simply run the command and specify the user account name first, and the user group name second. This makes the command look a little funny because you have to use “sudo” to run the command, and also specify the group name “sudo” at the end. The entire process is automatic once you press Enter, and looks like this:

nathan@ubuntu-book:∼$ sudo adduser alexander sudo
Adding user `alexander' to group `sudo' ...
Adding user alexander to group sudo
Done.

This change takes effect the next time the account logs in, so if Alexander were already logged in, he would have to log out before he could use sudo on the command line or confirm administrative tasks on the desktop.

With the adduser and passwd commands it’s easy to create new user accounts and set up passwords and administrator rights in seconds. If you spend time working on server tasks, you’ll find that these tools make adding users effortless.

Check Your Disk Space

You can use the command line to very quickly find out information about the amount of disk space you have available and how much is being utilized. This is faster than using the Disk Usage Analyzer because the commands are short and you can specify exactly what you want to know.

The best tool for a quick overview of free space on your computer is called df. Short for “disk free ,” it displays all of the file systems currently in use on your computer and size information for each of them. By default, the df command displays its sizes in 1,024-byte blocks, but by adding the -H option, the display uses a more human-readable format for the numbers.

nathan@ubuntu-book:∼$ df -H
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda1        15G   11G  3.5G  76% /
none            4.1k     0  4.1k   0% /sys/fs/cgroup
udev            510M  4.1k  510M   1% /dev
tmpfs           105M  1.3M  103M   2% /run
none            5.3M     0  5.3M   0% /run/lock
none            521M  156k  521M   1% /run/shm
none            105M   37k  105M   1% /run/user
/dev/sr1         25M   25M     0 100% /media/nathan/WD Unlocker
/dev/sdb2       606G  524G   83G  87% /media/nathan/My Passport

This is a nice summary of all mounted file systems, including some temporary ones used by the Ubuntu kernel. The system file system is 15 GB, and whether you want to know which device it’s running on, whether it contains 11 GB of data or has 3.5 GB free, or just a quick percentage utilized, everything’s right here. The last line contains information on the external drive, which has 83 GB available and is mounted at “/media/nathan/My Passport.” This is plenty of space for running backups, and I know where to find those files. The file systems that don’t start with /dev are used by Ubuntu and can be ignored.

A similar tool is du, which is short for “disk usage .” This tool prints an estimate of disk usage for the current directory and any directories it contains. Like df, the sizes are shown in 1024-byte block sizes, but you can use the “-si” option to make du print sizes in human-readable format. Running the du command shows all folders, even hidden folders and folders inside folders, so the output can be very long. Running the command in the Pictures folder shows the following output:

nathan@ubuntu-book:∼/Pictures$ du --si
550M    ./Cabrillo Beach
128M    ./2012/06/10
128M    ./2012/06
128M    ./2012
677M    .

The period (.) represents the current folder, which is “/home/nathan/Pictures.” The summary at the bottom shows that the current folder uses 677 MB, but adding up each of the totals comes to 934 MB. This seems wrong, until you notice that “/home/nathan/Pictures/2012” is empty except for the “06” folder inside it, which is again empty except for the “10” folder inside that contains the actual photos. The size of each folder includes the contents of the folders inside, but the summary at the bottom is correct.

You can also specify a folder path to point du to a different folder than the current location, or specify a file pattern, such as “*.jpg” to get file size information for files that match that pattern. Giving a file pattern shows space information on a per-file basis, and it might be useful to add “-c” to the options to ask du to show the total space used for all files. The display looks like this, with some lines removed for space considerations:

nathan@ubuntu-book:∼/Pictures/2012/06/10$ du --si -c *.jpg
295k    CRW_5777_CRW_embedded.jpg
279k    CRW_5778_CRW_embedded.jpg
...
377k    CRW_5800_CRW_embedded.jpg
7.7M    total
Note

df -H” and “du --si” display decimal storage units that match Ubuntu’s graphical applications that work with storage sizes. But if you prefer binary storage units such as KiB, MiB, and GiB, you can use “df -h” and “du -h” instead.

These two commands give you a quick look at how your computer’s storage space is being used, at both the overview level and the specific level. These are also tools that are helpful not only on a desktop system but when working with servers.

Edit Text Files

When spending time in a text-based interface, it makes sense to talk about editing text files. Traditionally, Unix and Linux programs have used text files to store their configuration settings. This allowed the file to be human readable and easy to set up, plus easy to change using text manipulation tools and input redirection using scripts. Today, many programs still store their settings as text files for the same reasons. Many documents were written in text files as well. With certain well-known exceptions, they are compatible with practically every operating system and easily shared with others. Formatting can be added with special markup such as TeX, HTML, and Markdown. There are many different text editors, and each has its own fans, but the easiest to start out with is definitely nano.

Note

Text editor choice tends to be contentious because people can spend a lot of time working with them. So it’s important to pick one that works best for your needs. This is so subjective, however, that countless debates have been fought (and still rage on) over the legendary One True Text Editor. Emacs and vi have steep learning curves but both are rewarding. Just know that comparisons online tend to be charged!

To start nano , you can run “nano” along with the name of a file to open. If you do not specify a file, nano will keep your text in memory until you save it to a file. Running nano will display the basic text editing interface (see Figure 5-2). The top line gives you information about the file you are editing (called a “buffer ”) in the center and whether the file has been modified on the right. The bottom three lines display a status bar that is normally blank, followed by two lines displaying commonly used shortcut keys. On this display, the caret (^) represents the Ctrl key, so ^G for the “Get Help” command represents Ctrl+G. You will also see references to M, which stands for the Meta key. You can use the Alt key as a stand-in for Meta. For example, where the help file specifies M-D as the shortcut to count the number of words, lines, and characters in the current file, you can press Alt+D.

A333290_2_En_5_Fig2_HTML.jpg
Figure 5-2. nano is an easy way to edit text files, with onscreen shortcut guides

Using nano is straightforward. You type, and your text appears on the screen. To move the cursor and scroll through help files, the arrow keys and Page Up and Page down keys work in addition to the shortcuts listed on the screen. You can use Ctrl+C to print the current position of your cursor in the file on the status line. This can help you orient yourself in a large file.

If you are using nano to edit a configuration file, you will note that it doesn’t wrap lines at the end of the screen but instead uses a dollar sign ($) to show that a line continues to the right of the screen. Placing your cursor on such a line allows you to scroll to the right with the right arrow or End key. The first character on the line will change to $ to indicate that the line extends to the left side of the screen. Configuration file entries must be on one line, so this helps ensure that they are being displayed properly.

If you are writing a document, however, you may want the display to wrap. You can press Alt+$ to turn on “soft” line wrapping. This allows you to see an entire line at once by displaying it on multiple lines without using actual end-of-line characters. This is useful when you are writing in text mode but will import your text to a word processor or other format when you are done.

One other useful feature about nano is that it understands some common text and configuration file formats, such as HTML, Python code, TeX documents, and many more. If you edit a file with an extension of “.html” or “.py,” for instance, nano will color code the text to help you identify keywords, variables, string literals, and notice other formatting issues that help protect against missing quotation marks or brackets. This can greatly enhance your editing experience without getting in your way.

When you are ready to save a file, press Ctrl+O to write the file out to disk. If you specified a file on the command line, nano will suggest the same file name and pressing Enter will overwrite it. The bottom two lines of the screen display several options as well. Entering a file name and pressing Alt+B will create a backup file, which will copy the original contents of the file to a new file with a tilde(∼) at the end before saving your changes to the original file name. By default, Files will not display backup files ending in tilde, but ls on the command line will. Pressing Ctrl+X will exit nano, which will prompt you to save a file if you have made any changes.

Editing text files is an important task on the command line, and there are dozens of different text editors designed to make this easy and efficient. Starting out, nano is a pleasant tool to use and is present by default on Ubuntu. You can use it to write anything, and it is a lightweight editor that loads instantly. Whether it’s your first command-line text editor or your favorite, nano will serve you well.

Read Email

Email has changed dramatically over the years. While Internet email as we know it today emerged in the early 1970s, early electronic mail messages were text-only messages that were passed from user mail folder to user mail folder on the same machine. Reading email in a text-only client can be a fun peek back in time that also delivers a unique perspective. Reading email in a text-only mail client is a much more focused experience than you might expect. However, one thing that has not aged very well is the setup process. While the setup on this is not for the faint of heart, the results are pretty fun. There are two popular terminal-based email clients today: Alpine and Mutt. I’m going to focus on Alpine, and you will need to install the “alpine” package via the command line. Type the following command at the command line and then press Enter to install alpine:

sudo apt install alpine

Type your password when prompted, and press Enter. Ubuntu will provide a list of additional software that will be installed along with the software. Simply press Enter at the confirmation prompt to accept the default of “Yes” and Ubuntu will download and install the software.

One legacy of Alpine is that while it is extremely configurable, it also expects certain information to be entered using specific formatting. The sheer number of configurations can be intimidating as well. The first thing you will need to know is your mail server details. This can be as simple as looking in Thunderbird or Evolution You’ll need your IMAP server and username to receive email, and your SMTP server and username to send email. You can always set up incoming mail and set up outgoing mail later.

To run Alpine, simply type the command “alpine” and press Enter. A welcome message will be displayed on the first run only, and you can press E or Enter to show the main menu. At the top of the menu it will show you the current folder—INBOX by default—and the number of unread messages. Each command can be activated by its shortcut key or by using the arrow keys to highlight a command and pressing Enter. The bottom two lines in the terminal show other commands that can be activated. First, you’ll want to press S to enter setup. Then press C to enter the configuration settings.

The two settings you need to change are “SMTP Server ” and “Inbox Path.” Both of these need to be formatted in a way that provides all relevant login information. Let’s assume that your IMAP server is “imap.example.com,” your SMTP server is “mtp.example.com”,  and your username is the same for both servers. Each connection setting is built in the same style.

imap.example.com/user=username

If you are using anything but the standard port , you add a colon (:) after the server name, and you can add /ssl or /tls after your username if you are using encryption. So if you were using SSL to encrypt your mail server connection, the “Inbox Path” setting would be

imap.example.com:465/user=username/ssl

Highlight the setting you wish to change, and press Enter to edit the field. Press Enter again to save the value. When you first set the “Inbox Path,” you will be prompted for the inbox folder. Press Enter to use the default of “inbox, and you’ll see that the path was changed to read

{imap.example.com/user=username}inbox

This is the standard format for specifying IMAP folders, and you can use it to point to folders for your sent mail folder (referred to in Alpine as “Fcc” or “file carbon copy”).

Once you have set up your mail servers, press E to exit setup. Alpine will ask you whether you want to save your configuration changes. None of the changes you have made will take effect until you choose “Commit changes” by pressing Y or pressing Enter.

When you exit setup, Alpine will attempt to connect to your mail server and will ask you for your password. Type it and press Enter, and after a few seconds you should see a status messages that your inbox folder is opened along with the total number of messages and the number of new messages. Press I to load the message index. It will display all messages in your current folder (see Figure 5-3).

A333290_2_En_5_Fig3_HTML.jpg
Figure 5-3. Email without distractions, the way it was in the mid-1990s—only now with Unicode support!

You can use the arrow keys to move the cursor up and down, and press Enter to read a message . The spacebar scrolls down one page and the minus (-) key scrolls back up one page. Note that messages are listed in order from the oldest at the top to the newest at the bottom. In addition to the Enter key, you can also use the greater than sign (>) to access an email or item and the less than sign (<) to go up one level again. Press C to create a new email or “r” to reply to the highlighted message. The bottom two lines of the screen show you a full list of commands, and you can cycle between the displayed commands by pressing the “o” key. Typing a question mark (?) will bring up the help file and will automatically jump to help on the highlighted object. This is especially useful in the settings screens.

When composing email messages, Alpine uses the pico text editor, and this is the program that inspired the GNU nano editor which you may already be familiar with. Commands are listed at the bottom of the screen and Ctrl+X will send your email once you are finished writing it. Ctrl+C will cancel the email. The bottom of the screen will prompt you to confirm your actions.

Another interesting way that workflow differed from the way it was in the past is that actions require extra confirmation. From the message index you can press D to delete a message, but they are marked as deleted and remain in your inbox. This gives you time to change your mind and press U to undelete them. It is not until you press X to “expunge” your folder that the deleted messages are actually removed. On any of the menus or folder or message lists, you can press Q to be prompted to quit Alpine.

The full-screen, text-based email interface in Alpine gives a classic, retro feel that evokes the standard behaviors of mainframes and terminals. What’s best of all is that it remains a very classic, efficient way to work with email today. The straightforward presentation and the text-based interface is more than able to stand in for more popular graphical email clients today.

Browse the Web

Some 25 years later, it’s hard to remember just how much the World Wide Web changed the Internet and the world at large. Online information retrieval systems used to be built to work with only specific software, and the information retrieved was often only accessible on the same computer architecture with the same authoring software. The Web changed all of that, with a flexible document language that allowed hypertext links to other documents. Because everything was primarily text-based, the documents could be displayed on any computer. These unique properties caused the Web to overtake other potential systems (particularly gopher) and grow into the phenomenon it is today.

A year before Mosaic arrived and two years before Netscape Navigator and Microsoft Internet Explorer appeared, a text-based web browser called links was created. It was a very popular alternative to the first graphical web browsers, since not all computer users had access to graphical terminals. Plus, it was fast and efficient and the early Web was mostly text-based as well. Links has been reimplemented several times, and today an enhanced version called ELinks is one of the most powerful and friendly text browsers around. Not only can it be used to experience the Web from the command line, but its menu system and mouse support make it a simple yet refreshing change from slow, graphics-laden web sites. You will need to install the “elinks” package via the command line. Type the following command at the command line and then press Enter to install elinks:

sudo apt install elinks

Type your password when prompted, and press Enter. Ubuntu will provide a list of additional software that will be installed along with the software. Simply press Enter at the confirmation prompt to accept the default of “Yes” and Ubuntu will download and install the software.

With its default settings, ELinks is very plain. The first time you run the command elinks, it lets you know that you can access the menus with the Escape key, and where to find documentation under the “Help” menu. Once you press Enter to dismiss that dialog, you are prompted for a URL. Just type in a web address and press Enter. Typing in “ www.google.com ” will take you to the Google home page, for example (see Figure 5-4). This might seem a bit underwhelming at first, but the minimalistic presentation can grow on you, especially if you’re looking up information in a hurry. You can also access a Web page immediately by supplying it on the command line, for example, typing “elinks http://www.ubuntu.com/ ” would open the Ubuntu web site by default.

A333290_2_En_5_Fig4_HTML.jpg
Figure 5-4. Google wasn’t around before 1998, but the Yahoo! and Alta Vista search engines looked much like this

The top line of the display is the title bar, and displays the title of the web page you are viewing as well as your current position, which is shown in screens full of text. You can press Escape or click the top line with your mouse to display the menu bar. Clicking the menu options will open each menu, or you can use the arrow keys to navigate the menus. In all menus and dialog boxes, the highlighted letter of each option can be used to activate that option, and most menu items will display a shortcut key on the right that can be pressed without entering the menus.

The monochrome, plain interface of ELinks cuts out distractions, and most commands are accessible with a single press of the keyboard. But it’s possible to make ELinks much more attractive as well. Open the menu by pressing Escape, type “s” to open the “Setup” menu, then type “t” to open the “Terminal Options” window. Then you can use the mouse or keyboard to enable color mode. If you are using ELinks in Ubuntu while using GNOME Terminal or Console, you should enable “256 colors” mode. If you are using ELinks using a virtual terminal, only 16 colors are supported. You can move the cursor with the arrow keys and activate a selection by pressing Enter, and activate the changes by typing “o” for “OK.” Or, you can click directly on each option to activate it. Once you test the settings out you can go back to the Terminal Options menu and click “Save” or type “v” to save your changes. ELinks will load saved settings the next time it is run.

Actually navigating web sites is simple. You can use the up and down arrows to move from link to link, and the PageUp and PageDown keys to scroll the web page. The active link will be highlighted, and the Enter key will follow a link. The status bar on the bottom of the terminal will display the link destination or information about the current image or text field. You can select radio buttons or text boxes by highlighting them and pressing the Enter key. Some web sites can be awkward to navigate because most navigation menus are implemented as HTML list elements, which show up as bulleted lists in ELinks, but after a little bit of practice, scrolling through to actual content and moving around become easy. And even though sites will look different, most well-designed web pages are still readable. The Ubuntu web site is a good example of a site that is accessible even in text format (see Figure 5-5).

A333290_2_En_5_Fig5_HTML.jpg
Figure 5-5. Carefully designed web pages like the Ubuntu site are usable even in text-only form

Once you’ve mastered the basics, ELinks has most of the features you’d expect in a modern web browser. The bookmark manager can be accessed by typing “s” and bookmarks can be visited, added, deleted, and more. Choosing “Add” will bring up a dialog box with the current page’s title and address filled in. The main surprise is that the move feature requires individual bookmarks to be selected before they can be moved. Bookmarks can be selected by highlighting them with the arrow keys and pressing the Insert key. Selected bookmarks will be marked with an asterisk (*).

ELinks also has tab support . Typing “t” opens a new tab and asks for a web address. Typing “T” while a link is selected will open that link in a background tab. Once more than one tab is visible, the tab bar appears above the status bar. It lists all open tabs and highlights the current tab. Clicking a tab name with the mouse switches to that tab, and the less than (<) and greater than (>) keys can be used to display the previous and next tab, respectively. Typing “c” closes the current tab. Documents will load in the background, so tabs are a great way to load a new page while you are still reading the current page.

The download manager appears when you click a downloadable link and chose the “Save” option. After setting a download location and filename and choosing “OK,” the download progress is displayed in a window over the page (see Figure 5-6). The file download can be moved to the background, where it can be checked through the download manager later. Choosing “Background with notify” will cause a dialog box to be displayed once the download is finished. The download manager can be accessed via the “Tools” menu or by typing “D” and will manage multiple downloads while ELinks is running. Notably, the “Abort” option will stop the download without deleting the file. The download can be resumed again later.

A333290_2_En_5_Fig6_HTML.jpg
Figure 5-6. Elinks has a built-in download manager to handle saving large files

While this covers most of the common features of ELinks, the documentation is easy to read and section 3 gives an overview of the user interface along with details on everyday usage, followed by detailed descriptions of the bookmark and tabs features in sections 4 and 5. You can read the Elinks manual online at http://elinks.or.cz/documentation/html/manual.html-chunked/index.html .

Browsing the Web has come a very long way in the last 25 years, and ELinks is an enhancement of the early text-based browser interfaces. Not only is it useful for testing web sites for accessibility and screen reader compatibility, but its speed and bookmark manager make it an interesting way to do research without distracting graphics. Mouse support and a powerful download manager help make it even more approachable for new users.

IRC

Internet Relay Chat is a real-time chat network that brings people together from around the globe. The protocol has been around since 1988 and has been used for socialization as well as coordination. Not only do Canonical employees and Ubuntu members use IRC to coordinate work and communicate during their workdays (see Figure 5-7), but the Ubuntu community also uses IRC to offer technical support, plan events, and simply relax and socialize. IRC support is included with Empathy on the desktop, but to use IRC on the command line you will need to install the “irssi” package via the command line. Type the following command at the command line and then press Enter to install irssi :

A333290_2_En_5_Fig7_HTML.jpg
Figure 5-7. Ubuntu developers using IRC on the desktop to discuss how to integrate an IRC client with phones
sudo apt install irssi

Type your password when prompted, and press Enter. Ubuntu will provide a list of additional software that will be installed along with the software. Simply press Enter at the confirmation prompt to accept the default of “Yes” and Ubuntu will download and install the software.

IRC servers allow users to log in and join other users in “channels” to discuss various topics. Each IRC server has its own administrators and rules of conduct. Servers can be linked together to form an IRC network. Connecting to any server on a network allows you to communicate with others users on the same network. Ubuntu uses the Freenode network for official channel hosting, and connecting to irc.ubuntu.com will cause your IRC client to connect to a random Freenode server around the world.

IRC clients display server messages in a live window at the top of the screen, and the bottom line is an input area where commands and messages can be edited before being sent with the Enter key. Commands begin with a slash (/) character on the first line, and any command not used by the client is sent to the server for processing. Any line not beginning with a slash is sent to the active IRC channel for others to read.

Connecting to a Server

The irssi command starts the irssi IRC client. The first time irssi is run, it will display a message that points you to https://www.irssi.org/ to find the “startup-HOWTO” under the site’s “Documentation” section. This file assumes the user is already familiar with other IRC clients but also gives some useful advice about configuring the software. Irssi also lists the two commands necessary to connect to Freenode (/connect irc.ubuntu.com) and join the official support channel (/join #ubuntu).

The first step is to connect to Freenode . Once you are connected, you will be able to join channels and talk to other people. By default, irssi will set your nickname (nick) to your username. If this name is already in use on Freenode, you will receive a message from NickServ, an automated Freenode service.

18:29 -NickServ(NickServ@services.)- This nickname is registered. Please choose a different nickname, or identify via /msg NickServ identify <password>.

If this appears, you can change your nick by using the /nick command. Simply type “/nick” followed by a space, and then a new nickname containing no spaces. The server will confirm the change.

18:30 -!- You're now known as nhaines            

Or, it will let you know that the nick is not available.

18:30 -!- Nick nhaines is already in use

If your Ubuntu login is in use on Freenode or you want to use a different nick, you can change the nick setting in irssi by typing “/set nick” followed by a space and the new nick. Irssi will remember this setting in the future when you connect to a server.

Once you have set up your nick, you can join a channel . If you are new to IRC, you can find a list of Ubuntu-related channels at https://wiki.ubuntu.com/IRC/ChannelList . The Ubuntu support channels are good ways of getting technical support, but they are busy and messages scroll by very quickly. The Ubuntu discussion channels are good places to chat with others on various Ubuntu- and non-Ubuntu-related topics, and the Ubuntu team channels are places where work is actively done on Ubuntu, usually during Western European business hours. The local Ubuntu channels are run by Local Community Teams and are a good way to meet other Ubuntu users near you.

IRC channel names begin with a hash sign (#) and you can join a channel by typing “/join” followed by a space and then typing the channel name. For example, typing “/join #ubuntu-offtopic” will join the #ubuntu-offtopic channel. A new “window” will open in irssi and you will see the channel topic and a list of users currently in the channel. Once you have joined the channel, you will see messages from other users. You can type a message and press Enter to send it to the channel. You can leave a channel by typing “/part” and pressing Enter.

Messages are sent to the entire channel at once, but there are several ways of directing messages to a certain user. When you use someone’s nick in a message, most IRC clients highlight your message for that user. In a busy room, this can be a good way to clarify that you are asking a question of or responding to a specific person. You can also send messages directly to other IRC users who are logged into the same network with the /query command. For instance, to send a private message (PM) to me on Freenode , you would type:

/query nhaines Hello, this is a private message

This will appear in a new irssi window. To close a non-channel window, you can type the “/win close” command.

Irssi uses separate windows to manage each channel. Window 1 is the status window and displays miscellaneous messages from the IRC server. The other windows display messages from channels or other users. You can switch windows by holding the Alt key while typing the number of the window. If this does not work, you can press and release the Escape key and then type the number of the window.

Ending your time on IRC is simple. “/part” can be used to close any channel, but “/disconnect” will close your connection with the IRC server. You can exit irssi with the “/quit” command.

IRC Etiquette

Every IRC network is independent and has its own rules, but IRC has been around for a very long time, and there are certain conventions that unique to communicating this way. They can catch you by surprise at times, but here are some pointers that will help you while using the Ubuntu channels on Freenode .

The most important thing to remember is that most channels are run independently from the IRC network they are on. An IRC network might have certain guidelines—for example, Freenode exists to support Free and open source software development. Individual channels may have additional guidelines. In particular, IRC is known for being very irreverent, snarky, and sometimes hostile. The official Ubuntu channels all enforce the Ubuntu Code of Conduct and welcome new users.

IRC is an asynchronous communication method . That means that while real-time conversation isn’t uncommon, a lot of IRC users will keep their client connected while they are away and check in periodically. This is called “idling ” in channel and means that not all of the users shown are actually paying attention to the channel. If you have a support question but see no other messages, you can leave your IRC client running and check in later to see if there are responses. It may even take hours, but if someone knows an answer they will see your message when they return to their computer. It may seem counterintuitive, but it’s better to ask a question in the public channel instead of sending a private message to an active user. He or she may be busy or may not have an answer, but the public message will be seen by more users.

A side effect of this is that other users generally won’t tell you if they don’t know an answer to a question. This doesn’t mean you are being ignored, but it does mean that they are being “polite” by staying quiet and allowing others to answer. Asking the same question repeatedly is seen as quite rude. On the other hand, many questions are very common. Sometimes asking a question will cause another user to type a “bot command,” which causes an automated response, such as a pointer to another channel. This isn’t meant to be dismissive, but is a way to quickly provide you with standard information.

Many IRC users consider it rude to send a private message someone you don’t know. While the /query command is useful and is a good way to continue off-topic conversations outside a channel, it’s best to ask permission before using it to contact someone new.

Some channels are workplaces. Ubuntu developers live all over the world and while the #ubuntu-touch channel is a very friendly place that is exciting to watch, sometimes developers are hard at work discussing the tasks they are working on. Sometimes when an active conversation is in progress, off-topic chatter can be a distraction. #ubuntu-offtopic is a channel that is always safe for random topics.

No matter the IRC channel , it’s helpful to read the channel topic and spend time observing the local “culture” and seeing how members treat each other. This will help you fit in and can prevent misunderstandings. For more information about the conduct expected while in official Ubuntu IRC channels and interacting with the community, please see https://wiki.ubuntu.com/IRC/Guidelines . It covers a lot of specific Ubuntu etiquette in detail.

Play Text-Based Games

While the other sections in this chapter show how you can get a lot of work done on the command line, there were also a lot of games written for a text environment, too. Many actually became classics that were expected to be found on any standard Unix system. Ubuntu contains a package called “ bsdgames ” which you can install via the command line. It contains 40 text games or toys that you can enjoy. Type the following command at the command line and then press Enter to install bsdgames:

sudo apt install bsdgames

Type your password when prompted, and press Enter. Ubuntu will provide a list of additional software that will be installed along with the software. Simply press Enter at the confirmation prompt to accept the default of “Yes” and Ubuntu will download and install the software.

While there are too many games to go over in detail, I would like to highlight a few of them. You can see the list of games installed by running the command “ls /usr/games” in a terminal after you have installed the bsdgames package. You can view the manual pages by typing “man” followed by a space and the name of the game. For example, running “man rain” describes rain as an animated raindrops display. This was used as a screen saver when text terminals were connected to mainframes. Running “rain -d 120” does display an entirely useless yet fairly hypnotic simulation of raindrops landing in a puddle. It’s easy to imagine a university student connected to a terminal, writing notes while the display updated (see Figure 5-8). Incidentally, the man page says the optimal speed is a terminal at 9600 baud. I first ran this program dialed into a Linux shell with a 2400 baud modem and couldn’t quit it. I had to hang up and dial back in again. You can use Ctrl+C to stop the animation and return to the command prompt, and you won’t have to wait four minutes while your modem catches up like I once did, either. The command worms is similarly a screensaver and is slightly more interesting. It’s also best used with “worms -d 120”, but the man page, which is read by running “man worms” has other options as well.

A333290_2_En_5_Fig8_HTML.jpg
Figure 5-8. This is pretty close to what “rain” looked like on a real terminal, long ago

There are many other curious utilities as well. All of them can be ended immediately with Ctrl+C. The bcd, ppt, and morse commands translate typed input into computer punch cards, older paper tape, or Morse code. You can create large banners that could be printed on an old line printer or dot matrix printer using continuous feed paper with printerbanner. arithmetic and quiz are memory tests. The command pom prints the current phase of the moon.

Other programs are full-fledged games. The backgammon game simulates the famous board game, and even contains rules and a tutorial you can use to learn to play. The game monop is very similar to a certain real estate board game, with the same rules, and can be played with multiple players. canfield, cribbage, and go-fish are the popular card games of the same name, and hangman and worm are other famous games. Notably, “worm” is the famous growing snake game made popular on early cell phones, but it moves much more slowly and is less stressful.

Other games are more elaborate. tetris-bsd is a falling block game, and used to require a fast modem to play. In the mid-1990s, some Linux installers would take an hour or more to install the operating system once it started copying packages. Some of them provided a running copy of this game on a second virtual console which could be played while you waited.

One of the most interesting games is Adventure , which is famous as the first interactive text adventure game to use natural language input. Running “adventure” places you on a path in the woods, between a brick shed and a stream. By typing in movement directions such as “north” or “go building,” the computer describes your surroundings. You can pick up and use items, and by following the stream south, you reach a grated entrance to Colossal Cave, filled with treasure, mystery, and danger. By exploring and solving puzzles, you progress through the game. It’s worth playing, because it is the direct ancestor of later graphical adventure games such as Beneath a Steel Sky, featured in Chapter 4 . A later text adventure game is also included, called battlestar. It has a very distinct feel from Adventure and is interesting in its own right.

Adventure’s cave is very closely based on Bedquilt Cave in Kentucky, but another very popular style of game became popular in 1980. A game called “Rogue allowed you to explore a series of dungeon levels that were randomly generated with each game. Others wrote copies of this game, adding features or taking inspiration from other sources. The most widespread clone or “rogue-like” game was called Hack . Running “hack” drops you into a dungeon with a pet. Together you must explore to the bottom of the dungeon to find a mysterious amulet, and survive the climb back to the top. The game prints a map of your surroundings represented by text characters, and you are only aware of objects in your line of sight, causing the game to expand and unfold as you explore. You’ll need to use the “?” key to access the in-game help to teach you the movement keys and other actions available.

Hack was released as an open source game, and another set of developers began to create a version that was named Nethack because the developers mostly communicated over the Internet. This version expanded on Hack to become legendary as a game with hundreds of monsters and items, and even more options. Where Hack is a difficult game to win, Nethack expanded on the formula in untold subtle ways, and it is worth installing and playing too. You can install the package “nethack-console” via the command line or Ubuntu Software. The game can then be run with the command “nethack”, and the help file and options available are much more detailed (see Figure 5-9). Type the following command at the command line and then press Enter to install Nethack:

A333290_2_En_5_Fig9_HTML.jpg
Figure 5-9. Nethack dungeons are revealed as you explore—as are the true natures of the items you find
sudo apt install nethack-console

Type your password when prompted, and press Enter. Ubuntu will provide a list of additional software that will be installed along with the software. Simply press Enter at the confirmation prompt to accept the default of “Yes” and Ubuntu will download and install the software.

Hack and Nethack use symbols to stand in for many different objects. You can use the slash (/) key to display a prompt where you can type a symbol and see what it stands for. In Nethack, you can use the cursor to highlight and identify an object on the map instead of typing the symbol. As you explore, you’ll find many items that you can use. Armor can be worn; weapons can be wielded. And as you move you’ll need to eat and drink. Food can be eaten and water drunk, but your supplies will wear thin. Sometimes you’ll find shops where you can buy items. Most of the time your adventurer will die suddenly. But each new game promises a unique experience, and plenty of surprises.

The bsdgames package fits a lot of entertainment into 2.5 MB of disk space . Some games stand the test of time, and others are now more interesting as peeks into an earlier time. But they shaped the free time and culture of the early Unix users that predated Linux and Ubuntu. And they are fun rewards for learning to use the command line.

Summary

The Linux command line isn’t as difficult or scary as it’s made out to be. While full mastery takes time and patience, there are many tasks that are easier or faster when performed with a text interface. Many commands offer easy-to-read output, and the results can be copied and saved or sent to a file or another program for further processing. And you can use the command line to tell the computer exactly what you want it to do, often saving time and frustration. When you’re comfortable on the command line, you have the ability to take advantage of a new way to interact with your computer whenever it is more convenient.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.233.43