Читать книгу LPIC-1 Linux Professional Institute Certification Study Guide - Richard Blum - Страница 12

Part I
Exam 101-400
Chapter 1
Exploring Linux Command-Line Tools
Understanding Command-Line Basics

Оглавление

Before you do anything else with Linux, you should understand how to use a Linux shell. The shell allows you to enter commands as needed. Which commands can be entered depends on which shell program is running. Several of the available shell programs are briefly described.

In using shell commands, you should also understand shell environment variables, which are placeholders for data that may be useful to many programs. Finally, it is helpful to know how to get help with the shell commands you're trying to use.

Exploring Your Linux Shell Options

The shell to be used for entering commands is configured for each individual user, and Linux provides a range of available shells. A complete shell list would be quite long, but the following shells are among the more common choices:

bash The GNU Bourne Again Shell (bash) is based on the earlier Bourne shell for Unix but extends it in several ways. In Linux, bash is the most common default shell for user accounts, and it's the one emphasized in this book and on the exam.

ShThe Bourne shell upon which bash is based goes by the name sh. It's not often used in Linux and the sh command is often a pointer to the bash shell or other shells.

tcsh This shell is based on the earlier C shell (csh). It's a fairly popular shell in some circles, but no major Linux distributions make it the default shell. Although it's similar to bash in many respects, some operational details differ. For instance, you don't assign environment variables the same way in tcsh as in bash.

csh The original C shell isn't used much on Linux, but if a user is familiar with csh, tcsh makes a good substitute.

ksh The Korn shell (ksh) was designed to take the best features of the Bourne shell and the C shell and extend them. It has a small but dedicated following among Linux users.

zsh The Z shell (zsh) takes shell evolution further than the Korn shell, incorporating features from earlier shells and adding still more.

In addition to these shells, dozens more obscure ones are available. In Linux, most users run bash because it is the most popular shell. Some other OSs use csh or tcsh as the default, so if your users have backgrounds on non-Linux Unix-like OSs, they may be more familiar with these other shells. You can change a user's default shell by editing their account, as described in Chapter 7, “Administering the System.”

Be aware that there are two types of default shells. The default interactive shell is the shell program a user uses to enter commands, run programs from the command line, run shell scripts, and so on. The other default shell type is a default system shell. The default system shell is used by the Linux system to run system shell scripts, typically at startup.

The file /bin/sh is a pointer to the system's default system shell – normally /bin/bash for Linux. However, be aware that, on some distributions, the /bin/sh points to a different shell. For example, on Ubuntu, /bin/sh points to the dash shell, /bin/dash.

Using a Shell

Linux shell use is fairly straightforward for anybody who's used a text-mode OS before: You type a command, possibly including options to it, and the computer executes the command. For the most part, Linux commands are external – that is, they're programs that are separate from the shell.

A few commands are internal to the shell, though, and knowing the distinction can be important. You should also know some of the tricks that can make using the command shell easier – how to have the computer complete a long command or filename, retrieve a command you've recently run, or edit a command you've recently used (or haven't yet fully entered).

Starting a Shell

If you log into Linux using a text-mode login screen, you have logged into a virtual console terminal and, most likely, you'll be dropped directly into your default shell. The shell program is what presents the prompt and accepts subsequent commands.

If you log into Linux using a graphical user interface (GUI) login screen, you'll have to start a terminal emulator manually in order to reach your default shell. Some GUIs provide a menu option, such as xterm or terminal, to start a terminal emulator program. These programs enable you to run text-mode programs within Linux, and by default they come up running your shell. If you can't find such a menu option, look for a menu option that enables you to run an arbitrary command. Select it, and type xterm or konsole as the command name. This will launch a terminal emulator program that will run a shell.

Once you start a terminal or log into a virtual console terminal, the shell will provide you with a prompt for entering commands. Remember that the shell is a program providing you with an interface to the Linux system.

A good first command to try, uname, will show what operating system is being run:


That's not too interesting. You can find out additional information by tacking on the -a option to the command. Be sure to include the necessary space between the command and the option:


The uname – a command provides a lot more information, including the current Linux kernel being used (2.6.32) as well as the system's hostname (server01.class.com). The uname command is an external command. The shell also provides internal commands. It's important to know the difference between the two command types, as explained in the next section.

Using Internal and External Commands

Internal commands are, as you might expect, built into the shell program. Thus they are also called built-in commands. Most shells offer a similar set of internal commands, but shell-to-shell differences do exist. Internal commands that you're likely to use enable you to perform some common tasks:

Change the Working Directory

Whenever you're running a shell, you're working in a specific directory. The cd command changes the current working directory. For instance, typing cd /home/sally changes the current working directory to the /home/sally directory.

You can use shortcut characters with the cd command as well. The tilde () character is a useful shortcut; it stands for your home directory. Thus typing cd ∼ will have the same effect as typing cd /home/sally if your home directory is /home/sally.

Display the Working Directory

The pwd command displays (“prints” to the screen) the current working directory. This command is helpful, especially after you have changed your working directory, to ensure you ended up in the right place.

Display a Line of Text

The echo command displays the text you enter. For instance, typing echo Hello causes the system to display the string Hello. This may seem pointless, but it's useful in scripts (described in Chapter 9, “Writing Scripts, Configuring Email, and Using Databases”), and it can also be a good way to review the contents of environment variables (described later in this chapter, in the section “Using Environment Variables”).

Time an Operation

The time command times how long subsequent commands take to execute. For instance, typing time pwd tells you how long the system took to execute the pwd command. The time is displayed after the full command terminates. Three times are displayed: total execution time (aka real time), user CPU time, and system CPU time. The final two values tell you about CPU time consumed, which is likely to be much less than the total execution time.

Set Options

In its most basic form, the set command displays a wide variety of options relating to bash shell operation. These options are formatted much like environment variables, but they aren't the same things. You can pass various options to set to have it affect a wide range of shell operations.

Terminate the Shell

The exit and logout commands both terminate the shell. The exit command terminates any shell, but the logout command terminates only login shells. Login shells are shell programs that are launched automatically when you initiate a text-mode login as opposed to those that run in xterm windows or other terminal emulators.

The preceding list isn't complete. Later sections of this chapter and later chapters describe some additional internal commands. Consult your shell's documentation for a complete list of its internal commands.

You can quickly determine if a command is a built-in command by using the type command. Just enter the command type before the name of the command you wish to check:


Some of these internal commands are duplicated by external commands that do the same thing. But those external commands aren't always installed on all systems. You can see if there are internal commands with installed duplicate external commands by using the -a option on the type command:


You can see that on this system, there is no external cd command installed. However, it does have an external pwd command installed.

Keep in mind that even when external commands are installed, the internal command takes precedence. To access the external command, you must provide the complete external command path, as in typing /usr/bin/time rather than time.


Confusion over Internal and External Commands

When duplicate internal and external commands exist, they sometimes produce subtly different results or accept different options. These differences may occasionally cause problems if you are unaware of them. For example, the time built-in command returns slightly different results than the /usr/bin/time external command:

As you can see, bash's internal time shows the time to execute the pwd command in a very nice format, while the external time command /usr/bin/time is not only a little sloppy in appearance, it also provides additional details. Be mindful of the potential behavior differences between internal and external commands.

When you type a command that's not recognized by the shell as one of its internal commands, the shell checks its path to find a program by that name to execute it. The path is a list of directories in which commands can be found. It's defined by the $PATH environment variable, as described shortly in “Using Environment Variables.” A typical user account has about half a dozen or so directories in its path. You can add and remove directories to the shell's path by changing the $PATH environment variable in a shell configuration file, as described in “Exploring Shell Configuration” later in this chapter.

You can run programs that aren't on the path by providing a complete path name on the command line. For instance, typing ./myprog runs the myprog program in the current directory. Typing /home/arthur/thisprog runs the thisprog program in the /home/arthur directory.


The root account should normally have a shorter path than ordinary user accounts. Typically, you'll omit directories that store GUI and other user-oriented programs from root's path in order to discourage use of the root account for routine operations. This minimizes the risk of security breaches related to buggy or compromised binaries being run by root. Most important, root's path should never include the current directory (./). Placing this directory in root's path makes it possible for a local troublemaker to trick root into running replacements for common programs. Omitting the current directory from ordinary user paths is also generally a good idea. If this directory must be part of the ordinary user path, it should appear at the end of the path so that the standard programs take precedence over any replacement programs in the current directory.

Whether you need to enter the path or not for a command, the program file must be marked as executable. This is done via the execute bit that's stored with the file. Standard programs are marked as executable when they're installed, but if you need to adjust a program's executable status, you can do so with the chmod command, as described in Chapter 4, “Managing Files.”

Performing Some Shell Command Tricks

Many users find typing commands to be tedious and error-prone. This is particularly true of slow or sloppy typists. For this reason, Linux shells include various tools that can help speed up operations. The first of these is command completion: Type part of a command or a filename (as an option to the command), and then press the Tab key. The shell tries to fill in the rest of the command or the filename. If just one command or filename matches the characters you've typed so far, the shell fills the rest of the command (or filename) for you and adds a space after it.

If the characters you've typed don't uniquely identify a command (or filename), the shell fills in what it can and then stops. Depending on the shell and its configuration, it may beep. If you press the Tab key again, the system responds by displaying the possible completions. You can then type another character or two and, if you haven't completed the command (or filename), press the Tab key again to have the process repeat.

The most fundamental Linux commands have fairly short names —mv, ls, set, and so on. However, some other commands are much longer, such as traceroute or service – status-all. Filenames can also be quite lengthy – up to 255 characters on many filesystems. Thus command completion can save a lot of time when you're typing. It can also help you avoid typos.


The most popular Linux shells, including bash and tcsh, support command and filename completion. Some older shells, though, don't support this helpful feature.

Another useful shell shortcut is history. The shell history keeps a record of every command you type. If you've typed a long command recently and want to use it again or use a minor variant of it, you can pull the command out of the history.

There are several rather easy methods to retrieve commands. It comes down to determining the method you like best:

Retrieve a Command

The simplest way to do this is to press the Up arrow key on your keyboard; this brings up the previous command. Pressing the Up arrow key repeatedly moves through multiple commands so you can find the one you want. If you overshoot, press the Down arrow key to move down the history. The Ctrl+P and Ctrl+N keystrokes double for the Up and Down arrow keys, respectively.

Search for a Command

Press Ctrl+R to begin a backward (reverse) search, and begin typing characters that should be unique to the command you want to find. The characters you type need not be the ones that begin the command; they can exist anywhere in the command. You can either keep typing until you find the correct command or, after you've typed a few characters, press Ctrl+R repeatedly until you find the one you want.

The Ctrl+S keystroke is used to search forward in the command history. You can press the Ctrl+S keystroke while using the backward search. This reverses the history search from backward to forward. If you used a backward search and have passed by what you need, then this keystroke is useful.

If the Ctrl+S keystroke causes your terminal to hang, press Ctrl+Q to resume terminal operations. To keep your terminal from hanging when Ctrl+S is used, type stty – ixon at the command line.

In either event, if you can't find the command you want or if you change your mind and want to terminate the search, press Ctrl+G to do so.

Frequently, after finding a command in the history, you want to edit it. The bash shell, like many shells, provides editing features modeled after those of the Emacs editor:

Move within the Line

Press Ctrl+A or Ctrl+E to move the cursor to the start or end of the line, respectively. The Left and Right arrow keys move within the line a character at a time. Ctrl+B and Ctrl+F do the same, moving backward and forward within a line. Pressing Ctrl plus the Left or Right arrow key moves backward or forward a word at a time, as does pressing Esc and then B or F.

Delete Text

Pressing Ctrl+D or the Delete key deletes the character under the cursor. Pressing the Backspace key deletes the character to the left of the cursor. Pressing Ctrl+K deletes all text from the cursor to the end of the line. Pressing Ctrl+X and then Backspace deletes all of the text from the cursor to the beginning of the line.

Transpose Text

Pressing Ctrl+T transposes the character before the cursor with the character under the cursor. Pressing Esc and then T transposes the two words immediately before (or under) the cursor.

Change Case

Pressing Esc and then U converts text from the cursor to the end of the word to uppercase. Pressing Esc and then L converts text from the cursor to the end of the word to lowercase. Pressing Esc and then C converts the letter under the cursor (or the first letter of the next word) to uppercase, leaving the rest of the word unaffected.

Invoke an Editor

You can launch a full-fledged editor to edit a command by pressing Ctrl+X followed by Ctrl+E. The bash shell attempts to launch the editor defined by the $FCEDIT or $EDITOR environment variable, or it launches Emacs as a last resort.

These editing commands are just the most useful ones supported by bash. In practice, you're likely to make heavy use of command and filename completion, the command history, and perhaps a few editing features.


If you prefer the vi editor to Emacs, you can use a vi-like mode in bash by typing set – o vi. (vi is described in Chapter 5, “Booting Linux and Editing Files.”)

The history command provides an interface to view and manage the history. Typing history alone displays all of the commands in the history (typically the latest 500 commands).

To retrieve the last command in your shell history, type !! and press Enter. This will not only show you the command you recalled but execute it as well:


You can execute a command by number via typing an exclamation mark followed by its number, as in !210 to execute command 210. Typing history – c clears the history, which can be handy if you've recently typed commands you'd rather not have discovered by others, such as commands that include passwords.

The bash history is stored in the .bash_history file in your home directory. This is an ordinary plain-text file, so you can view it with a text editor or a command such as less (described later, in “Paging through Files with less”).


Because your bash history is stored in a file, it can be examined by anybody who can read that file. Some commands enable you to type passwords or other sensitive data on the same line as the commands themselves, which can therefore be risky. The ∼/.bash_history file does not record what you type in response to other programs' prompts, just what you type at the bash prompt itself. Thus, if you have a choice, you should let commands that require passwords (or other sensitive data) prompt you to enter this data rather than enter such information as options to the command at the bash prompt.

In Exercise 1.1, you'll experiment with your shell's completion and command-editing tools.

Exercise 1.1

Editing Commands

To experiment with your shell's completion and command-editing tools, follow these steps:

1. Log in as an ordinary user.

2. Create a temporary directory by typing mkdir test. (Directory and file manipulation commands are described in more detail in Chapter 4.)

3. Change into the test directory by typing cd test.

4. Create a few temporary files by typing touch one two three. This command creates three empty files named one, two, and three.

5. Type ls – l t and, without pressing the Enter key, press the Tab key. The system may beep at you or display two three. If it doesn't display two three, press the Tab key again and it should do so. This reveals that either two or three is a valid completion to your command, because these are the two files in the test directory whose filenames begin with the letter t.

6. Type h, and again without pressing the Enter key, press the Tab key. The system should complete the command (ls – l three), at which point you can press the Enter key to execute it. (You'll see information on the file.)

7. Press the Up arrow key. You should see the ls – l three command appear on the command line.

8. Press Ctrl+A to move the cursor to the beginning of the line.

9. Press the Right arrow key once, and type es (without pressing the Enter key). The command line should now read less – l three.

10. Press the Right arrow key once, and press the Delete key three times. The command should now read less three. Press the Enter key to execute the command. (Note that you can do so even though the cursor isn't at the end of the line.) This invokes the less pager on the three file. (The less pager is described more fully later in “Paging through Files with less.”) Because this file is empty, you'll see a mostly empty screen.

11. Press the Q key to exit from the less pager.

Exploring Shell Configuration

Shells, like many Linux programs, are configured through files that hold configuration options in a plain-text format. The bash configuration files are actually bash shell scripts, which are described more fully in Chapter 9. A couple of examples of these configuration files are ∼/.bashrc and /etc/profile.

Even without knowing much about shell scripting, you can make simple changes to these files. Edit them in your favorite text editor, and change whatever needs changing. For instance, you can add directories to the $PATH environment variable, which takes a colon-delimited list of directories.


Be careful when changing your bash configuration files, particularly the global bash configuration files. Save a backup of the original file before making changes, and test your changes immediately by logging in using another virtual terminal. If you spot a problem, revert to your saved copy until you determine the problem's causes and create a working file.

Using Environment Variables

Environment variables are like variables in programming languages – they hold data to be referred to by the variable name. Environment variables differ from programs' internal variables in that they're part of the program's environment, and other programs, such as the shell, can modify this environment. Programs can rely on environment variables to set information that can apply to many different programs. For instance, many text-based programs need to know the capabilities of the terminal program you use. This information is conveyed in the $TERM environment variable, which is likely to hold a value such as xterm or linux. Programs that need to position the cursor, display color text, or perform other tasks that depend on terminal-specific capabilities can customize their output based on this information.

Chapter 9 describes environment variables and their manipulation in more detail. For the moment, you should know that you can set them in bash by using an assignment (=) operator followed by the export command. A fun environment variable to change is the $PS1 variable. It modifies your shell prompt:


You can combine these two commands into a single form:


Either method sets the $PS1 environment variable to a new setting. When setting an environment variable, you omit the dollar sign, but subsequent references include a dollar sign to identify the environment variable as such. Thereafter, programs that need this information can refer to the environment variable. In fact, you can do so from the shell yourself using the echo command:


An echo of the $PS1 variable value can be a little confusing because it just shows your current prompt setting. However, you can get a better feel for displaying an environment variable by viewing the $PATH variable using echo:


That's a little better. Remember, the $PATH environment variable provides the shell with a directory list to search when you're entering command or program names.


Some environment variables, including the $PATH environment variable, are set automatically when you log in via the shell configuration files. If a program uses environment variables, its documentation should say so.

You can also view the entire environment by typing env. The result is likely to be several dozen lines of environment variables and their values. Chapter 9 describes what many of these variables are in more detail.

To delete an environment variable, use the unset command. The command takes the name of an environment variable (without the leading $ symbol) as an option. For instance, unset PS1 removes the $PS1 environment variable. But if you do this, you will have no shell prompt!

Getting Help

Linux provides a text-based help system known as man. This command's name is short for manual, and its entries (its man pages) provide succinct summaries of what a command, file, or other feature does. For instance, to learn about man itself, you can type man man. The result is a description of the man command.

To peruse the manual pages for a particular command or topic, you type man followed by the command or topic as an option. For example, to read about the export command, you would type man export at the prompt. If you wanted to learn more about the shell built-in (internal) commands, you would type man builtin at the prompt.

The man utility uses the less pager by default to display information. This program displays text a page at a time. Press the spacebar to move forward a page, Esc followed by V to move back a page, the arrow keys to move up or down a line at a time, the slash (/) key to search for text, and so on. (Type man less to learn all the details, or consult the upcoming section “Paging through Files with less.”) When you're done, press Q to exit less and the man page it's displaying.

You aren't stuck using the less pager with the man utility. You can change the pager by using the -P option. For example, if you decided to use the more pager instead to look up information on the uname command, you would type man – P /bin/more uname at the shell prompt.

Occasionally, the problem arises where you can't remember the exact name of a command to look up. The man utility has an option to help you here. You can use the -k option along with a keyword or two to search through the man pages:


The returned information (shown as a partial listing above) can give you some clues as to your desired command name. Be aware that poor keyword choices may not produce the results you seek.


On some older Linux distributions, you may get no results from a man utility keyword search. This is most likely due to a missing whatis database. The whatis database contains a short description of each man page, and it is necessary for keyword searches. To create it or update it, type makewhatis at the prompt. You will need to do this as superuser, and it may take several minutes to run.

Linux man pages are organized into several sections, which are summarized in Table 1.1. Sometimes a single keyword has entries in multiple sections. For instance, passwd has entries under both section 1 and section 5. In most cases, man returns the entry in the lowest-numbered section, but you can force the issue by preceding the keyword by the section number. For instance, typing man 5 passwd returns information on the passwd file format rather than the passwd command.


Table 1.1 Manual sections


Some programs have moved away from man pages to info pages. The basic purpose of info pages is the same as that for man pages. However, info pages use a hypertext format so that you can move from section to section of the documentation for a program. Type info info to learn more about this system.

There are also pages specifically for the built-in (internal) commands called the help pages. To read the help pages for a particular built-in command, type help command. For instance, to get help on the pwd command, type help pwd at the shell prompt. To learn more about how to use the help pages, type help help at the shell prompt.

The man pages, info pages, and help pages are usually written in a terse style. They're intended as reference tools, not tutorials! They frequently assume basic familiarity with the command, or at least with Linux in general. For more tutorial information, you must look elsewhere, such in books or on the Web.

LPIC-1 Linux Professional Institute Certification Study Guide

Подняться наверх