Basic use of a shell is fairly straightforward:Type a command and the shell responds by executing that command. To getthe most out of any text-mode interaction with Linux, though, you needto know how to use a shell's more advanced features. Ultimately, mostinteractive shell features boil down to ones that save you time, butsome features enable you to change the shell's appearance and the namesof its commands.
Time-Saving Shell Tricks
Unix shells support many features that systemadministrators and programmers have found valuable. These features helpsave time by automatically completing commands, by enabling you to runcommands you've run before with minimal effort, and by supportingediting of commands you're typing. From early in Unix history, shellshave supported features that enable capturing output from programs orsending a file as input to a program, as well as sending one command'soutput to a second one as input. Naturally, Linux's shells incorporatethese features.
Typing Partial Commands: Command Completion
Typing long commands or filenames can slow downcommand-line operations, both by adding to typing time and byincreasing the odds of a typo, thereby causing a command to fail orhave unintended consequences. Thus, bash and many other shells support a feature known as command completion.Type the first few letters of a command or filename and then press theTab key. The shell locates all of the possible matching commands on thepath or filenames that match. If just one command or filename matches,the shell fills out the rest of the command. If more than one commandor filename matches, the shell beeps, displays all the matching names,or both, depending on the shell's configuration. If no files match thespecified letters, the shell beeps.
For instance, at a command prompt, try typing chm and then the Tab key. The shell should respond by completing the command name: chmod. You can then enter a parameter for the command, making the text you see chmod 0644.If you then type a single letter for a filename and press Tab again,the shell may beep, display a list of files that begin with thatletter, or fill in a complete filename.
You can configure whether the shell displays all of the matching filenames or simply beeps by adjusting the /etc/inputrc file. If you want bash to display a list of files, add the following line to inputrc:
set show-all-if-ambiguous on
If this feature is turned off, bash merely beeps when more than one file matches; pressing the Tab key again causes the display of matching files to appear.
Rerunning Commands: History
As you work in a shell, chances are you'll findyourself wanting to issue the same commands, or minor variants of them,again and again. For instance, you might try to install a package , only to discover that you first need to addanother package. After you add the depended-upon package, you'll wantto add the first one. You can use a popular shell feature to simplifythis task: history. Most modern shellsmaintain a record of the most recently typed commands. You can movethrough these commands by pressing the Up Arrow and Down Arrow keys.For the benefit of Emacs fans, the Ctrl+P and Ctrl+N keys perform thesesame actions. When you find the command you want to use, press theEnter key or edit the command, as described in the next section,
You can also search through the history. Type Ctrl+R, and bash will display the following prompt:
(reverse-I-search)`ยด:
Type the first few characters of the command you wantto find, and the system will locate the best match. Type Ctrl+R againto search further back in the history.
Modifying Commands: Editing
Shells include simple editing features forcommands you type. You can use these features to correct errors as youtype commands, or you can use them to modify commands retrieved fromthe shell history, further expanding the utility of the historyfeature. The editing features in bash are modeled after those in Emacs. summarizes the most important of these commands.
Mastering these commands can be quite useful. Forinstance, suppose you discover that you've mistyped the secondcharacter of a command. Instead of retyping the entire command, you canpress Ctrl+A to move the cursor to the start of the line, move theRight Arrow key to move forward one character, press Delete to deletethe flawed character, type the correct character in its place, andpress the Enter key to enter the new command. Instead of retypingpotentially dozens of characters, your correction takes just fivekeystrokes.
Running Multiple Programs: Background Operations
Even in text mode, you can run multiple programs in Linux. One tool for doing this is the ampersand operator (&).Append this character to the end of a command and Linux launches theprogram in the background; the program runs, but you retain control ofthe terminal from which you launched the program. Of course, thisaction makes more sense for some programs than for others—launching atext-mode text editor in this way doesn't make much sense, forinstance, because you need to interact with the program. A program thatjust processes data and doesn't produce any console output, though, maybe profitably launched in the background. You could launch dd in this way, for instance, to copy a floppy disk image to a file while still retaining control of your console:
$ dd if=/dev/fd0 of=floppy.img &
You can also launch X programs in this way; when so launched, the program doesn't take over your xterm window, although it may still direct some output to the xterm. If you omit the ampersand, you can't use the xterm window until the X program finishes its work.
Once a program is running, you can usually kick itinto the background by pressing Ctrl+Z. The program suspends operations(it stops whatever it was doing, even if it was a CPU-intensivecomputation), and you can type new commands at your shell. Typing bg at this point puts the program in the background, much as if you'd launched it with an ampersand. Typing fg brings the program back to the foreground.
Manipulating Input and Output: Redirection
Text-mode Linux programs operate on three input/output streams, each of which is treated much like a file: Standard input (stdin) is normally tied to the keyboard and is the method programs use to accept input from the user. Standard output (stdout) is normally tied to the screen, xterm window, or other text-mode display tool, and it displays normal program output. Standard error (stderr)is also usually tied to the text-mode display, but it handleshigh-priority messages such as error reports. Linux can readilyredirect these input and output streams. Therefore, you can capture theoutput of a text-mode program in a file or send the contents of a fileto a program as input. You do this by using redirection operators, asdetailed in .
Each operator takes a filename as a parameter. You can combine multiple operations. For instance, to pass the contents of data.txt to numcrunch and to save the program's output in out.txt, you could type:
$
numcrunch < data.txt > out.txt
Combining Commands: Pipes
Pipes are a way to link programs together. Thefirst program's standard output is redirected to the second program asstandard input. The chain can continue for as many programs as youlike. The pipe operator is a vertical bar (|), so a piped series of commands looks like this:
$
ps ax | grep gdm
This example takes the output of ps ax and pipes it into grep, which searches for lines containing the string gdm. Using grepin this way can be a good way to trim a verbose program's output downto size. You may also want to pipe textual output through the less pager, enabling you to peruse the output at a human pace.
Customizing Your Shell
People don't have the same preferences, andLinux's shells were designed with this fact in mind—they supportcustomizations through a variety of configuration options. You canmodify system defaults to suit your needs as a site and modifyuser-specific options to change the behavior in your account alone. Twocommon types of customization are using aliases, which enable you to create shortcuts or effectively change the defaults of a command, and setting environment variables, which provide information to shells and to other programs you run from shells.
Finding Configuration Files
Each shell has its own unique set of configuration files. System-wide configuration files usually reside in /etc,and user-specific configuration files are found in users' homedirectories. Both system-wide and user-specific configuration filescome in two varieties:
login configuration files and non-loginconfiguration files. Login files apply only to shells launched by alogin process, such as a remote Secure Shell (SSH) login or a login ata text-mode console. Non-login configuration files apply to shells thataren't login shells, such as xterm windows launched from a GUI environment or a shell obtained by using su to change the login user's identity. summarizes the locations of bash configuration files.
In practice, is just a starting point; it's possible for a configuration file to sourceanother file, meaning to call the additional file. This is possiblebecause these files are really shell scripts, so you can do anything inthese files that you can do in any shell script. One example ofsourcing is in the common practice of placing program-specificconfigurations in the /etc/profile.dsubdirectory. Programs that require particular environment variablescan place appropriate scripts to set those variables in this directory.Mandrake, Red Hat, Slackware, and SuSE all use this approach, butDebian doesn't by default.
In addition to these common login files, other files can run programs when you log out. Specifically, ~/.bash_logoutdoes this for individual users. You might use this file to run programsthat delete sensitive temporary files, shut down any openPoint-to-Point Protocol (PPP) links to the Internet, or perform someother task.
Using Aliases
One common shell customization is settingaliases, which enable you to type shorthand versions of commands orconfigure the shell to automatically add certain parameters tocommands. For instance, the default behavior of the cp command is to overwrite files that match the target filename without prompting. If you prefer to have cp prompt you before overwriting an existing file, you could enter the following line in a bash startup script:
alias cp='cp -i'
This line tells bash to silently substitute cp -i whenever you type cp. You can also create a shorthand for a command; for instance, if you prefer to type lo instead of logout, you could create an alias like this:
alias lo='logout'
You normally place aliases in non-login file locations—/etc/bashrc, ~/.bashrc,or the like. This practice ensures that the aliases will be availablewhenever you launch a shell, whether or not it's a login shell. If youdon't want to use an alias on a one-time basis, you can do so in acouple of ways. First, you can surround the command in double quotes,as in "cp" file1 file2 to use cp without -i to copy the file. Second, you can type the complete path to the original executable, as in /bin/cp file1 file2.
Setting Environment Variables
Environment variables are pieces of data thatLinux makes available to programs you run. For instance, a Usenet newsreader needs to know the address of the news server from which itshould retrieve messages. Some programs use program-specificconfiguration files for this purpose, but others rely on environmentvariables. The NNTPSERVER environmentvariable, for instance, holds the name of a Usenet news server. Usingenvironment variables for this purpose makes sense when there areseveral programs that might use the information—you only need to setthe environment variable once, and if all the programs know to accessthat variable for the relevant information, you're done. Some programsrely on environment variables even for program-specific settings, soyou might need to set environment variables even for individualprograms.
To set an environment variable, use the export command in a bash startup script, as in:
export NNTPSERVER=news.luna.edu
You can reference existing environment variables whensetting a new one by preceding the existing environment variable with adollar sign ($). For instance, one important environment variable is PATH,which specifies the directories in which Linux searches for programswhen you type their names. Each directory is separated from itsneighbors by a colon (
. You can add a directory to PATH with a command like this:
export PATH=$PATH:/opt/OpenOffice.org/program
By convention, environment variables are all-uppercase. Variables used by a single bash script, ,"are lowercase or mixed case. If you need to set an environment variablefor a program, you should describe that variable in its documentation.You can then add the variable to a global or local configuration file,as appropriate.
Changing the Prompt
A shell presents a prompt when it's ready to receive input. You can change this prompt by setting the PS1 variable. For instance, if you want a simple $ prompt with no other adornment, you could type the following command:
$ PS1="$ "
Chances are you'll want to use assorted variables in defining your prompt. (check the bash man page for more). A backslash (\) identifies the following character as a variable. Most Linux distributions use [\u@\h \W]\$,or something similar, as their default prompt. This string results in aprompt ending in a dollar sign for ordinary users, and a hash mark (#) replaces the dollar sign for root logins.