Using the Shell in Linux


When you type a command in a shell, you can also include other characters that change or add to how the command works. In addition to the command itself, these are some of the other items that you can type on a shell command line:

  • Options — Most commands have one or more options you can add to change their behavior. Options typically consist of a single letter, preceded by a dash. You can also often combine several options after a single dash. For example, the command ls -la lists the contents of the current directory. The -l asks for a detailed (long) list of information, and the -a asks that files beginning with a dot (.) also be listed. When a single option consists of a word, it is usually preceded by a double dash (--). For example, to use the help option on many commands, you would enter --help on the command line. Here's an example of help information for the ls command (Output is piped to the less command to page through it; type q to quit):

    $ ls --help | less  Usage: ls [OPTION]... [FILE]...  List information about the FILEs (the current directory by default).  Sort entries alphabetically if none of the -cftuSUX nor --sort.      Mandatory arguments to long options are mandatory for short options too    -a, --all                  do not hide entries starting with .    -A, --almost-all           do not list implied . and ..      .      .      . 

  • Arguments — Many commands also accept arguments after any options are entered. An argument is an extra piece of information, such as a filename, that can be used by the command. For example, cat /etc/passwd displays the contents of the /etc/passwd file on your screen. In this case, /etc/passwd is the argument.

  • Environment variables — The shell itself stores information that may be useful to the user’s shell session in what are called environment variables. Examples of environment variables include $SHELL (which identifies the shell you are using), $PS1 (which defines your shell prompt), and $MAIL (which identifies the location of your mailbox).

    Tip 

    You can check your environment variables at any time. Type declare to list the current environment variables. Or you can type echo $VALUE, where VALUE is replaced by the name of a particular environment variable you want to list.

  • Metacharacters — These are characters that have special meaning to the shell. Metacharacters can be used to direct the output of a command to a file (>), pipe the output to another command (|), or run a command in the background (&), to name a few. Metacharacters are discussed later in this chapter.

To save you some typing, there are shell features that store commands you want to reuse, recall previous commands, and edit commands. You can create aliases that allow you to type a short command to run a longer one. The shell stores previously-entered commands in a history list, which you can display and from which you can recall commands. This is discussed further in the remainder of this section.

Unless you specifically change to another shell, the bash shell is the one you use with Fedora. The bash shell contains most of the powerful features available in other shells. Although the description in this chapter steps you through many bash shell features, you can learn more about the bash shell by typing man bash. For other ways to learn about using the shell, refer to the sidebar "Getting Help with Using the Shell."

Locating commands

If you know the directory that contains the command you want to run, one way to run it is to type the full path to that command. For example, you run the date command from the /bin directory by typing:

 $ /bin/date 

Of course, this can be inconvenient, especially if the command resides in a directory with a long name. The better way is to have commands stored in well-known directories, and then add those directories to your shell’s PATH environment variable. The path consists of a list of directories that are checked sequentially for the commands you enter. To see your current path, type the following:

 $ echo $PATH  /usr/local/bin:/bin:/usr/bin:/usr/X11R6/bin:/home/chris/bin 

The results show the default path for a regular Linux user. Directories in the path list are separated by colons. Most user commands that come with Linux are stored in the /bin, /usr/bin, or /usr/local/bin directories. Although most graphical commands (that are used with GUIs) are contained in /usr/bin, there are some special X commands that are in /usr/bin/X11 and /usr/X11R6/bin directories. The last directory shown is the bin directory in the user’s home directory.

Tip 

If you want to add your own commands or shell scripts, place them in the bin directory in your home directory (such as /home/chris/bin for the user named chris). This directory is automatically added to your path. So as long as you add the command to your bin with execute permission (described in the "Understanding file permissions" section), you can immediately begin using the command by simply typing the command name at your shell prompt.

image from book
Getting Help with Using the Shell

When you first start using the shell, it can be intimidating. All you see is a prompt. How do you know which commands are available, which options they use, or how to use more advanced features? Fortunately, lots of help is available. Here are some places you can look to supplement what you learn in this chapter:

  • Check the PATH — Type echo $PATH. You see a list of the directories containing commands that are immediately accessible to you. Listing the contents of those directories (with the ls command) displays most standard Linux commands.

  • Use the help command — Some commands are built into the shell, so they do not appear in a directory. The help command lists those commands and shows options available with each of them. (Type help | less to page through the list.) For help with a particular built-in command, type help command, replacing command with the name that interests you. The help command only works with the bash shell.

  • Use --help with the command — Many commands include a - -help option that you can use to get information about how the command is used. For example, type date --help | less. The output shows not only options, but also time formats you can use with the date command.

  • Use the man command — To learn more about a particular command, type man command. (Replace command with the command name you want.) The command name man is short for manual. A description of the command and its options appears on the screen.

image from book

If you are the root user, directories containing administrative commands are in your path. These directories include /sbin and /usr/sbin.

The path directory order is important. Directories are checked from left to right. So, in this example, if there is a command called foo located in both the /bin and /usr/bin directories, the one in /bin is executed. To have the other foo command run, you either type the full path to the command or change your PATH variable. (Changing your PATH and adding directories to it are described later in this chapter.)

Not all the commands that you run are located in directories in your PATH. Some commands are built into the shell. Other commands can be overridden by creating aliases that define any commands and options that you want the command to run. There are also ways of defining a function that consists of a stored series of commands. Here is the order in which the shell checks for the commands you type:

  1. Aliases — Names set by the alias command that represent a particular command and a set of options. (Type alias to see what aliases are set.) Often, aliases allow you to define a short name for a long, complicated command.

  2. Shell reserved word — Words that are reserved by the shell for special use. Many of these are words that you would use in programming-type functions, such as do, while, case, and else.

  3. Function — A set of commands that are executed together within the current shell.

  4. Built-in command — A command that is built into the shell.

  5. File system command — This is a command that is stored in and executed from the computer’s file system. (These are the commands that are indicated by the value of the PATH variable.)

To find out where a particular command is taken from, you can use the type command. (If you are using a shell other than bash, use the which command instead.) For example, to find out where the bash shell command is located, type the following:

 $ type bash bash is /bin/bash 

Try these few words with the type command to see other locations of commands: which, case, and return. If a command resides in several locations, you can add the -a option to have all the known locations of the command printed.

Tip 

Sometimes you run a command and receive an error message that the command was not found or that permission to run the command was denied. In the first case, check that you spelled the command correctly and that it is located in your PATH. In the second case, the command may be in the PATH, but may not be executable. Adding execute permissions to a command is described later in this chapter.

Rerunning commands

It’s annoying, after typing a long or complex command line, to learn that you mistyped something. Fortunately, some shell features let you recall previous command lines, edit those lines, or complete a partially typed command line.

The shell history is a list of the commands that you have entered before. Using the history command, you can view your previous commands. Then, using various shell features, you can recall individual command lines from that list and change them however you please.

The rest of this section describes how to do command-line editing, how to complete parts of command lines, and how to recall and work with the history list.

Command line editing

If you type something wrong on a command line, the bash shell ensures that you don’t have to delete the entire line and start over. Likewise, you can recall a previous command line and change the elements to make a new command.

By default, the bash shell uses command-line editing that is based on the emacs text editor. So, if you are familiar with emacs, you probably already know most of the keystrokes described here.

Tip 

If you prefer the vi command for editing shell command lines, you can easily make that happen. Add the line

set -o vi 

to the .bashrc file in your home directory. The next time you open a shell, you can use vi commands (as described in the tutorial later in this chapter) to edit your command lines.

To do the editing, you can use a combination of control keys, meta keys, and arrow keys. For example, Ctrl+F means to hold the control key and type f. Alt+F means to hold the Alt key and type f. (Instead of the Alt key, your keyboard may use a Meta key or the Esc key instead. On a Windows keyboard, you can sometimes use the Windows key.)

To try out a bit of command-line editing, type the following command:

$ ls /usr/bin | sort -f | less 

This command lists the contents of the /usr/bin directory, sorts the contents in alphabetical order (regardless of upper- and lowercase), and pipes the output to less (so you can page through the results). Now, suppose you want to change /usr/bin to /bin. You can use the following steps to change the command:

  1. Press Ctrl+a. This moves the cursor to the beginning of the command line.

  2. Press Ctrl+f or the right arrow ( ® ) key. Repeat this command a few times to position the cursor under the first slash (/).

  3. Press Ctrl+d. Type this command four times to delete /usr.

  4. Press Enter. This executes the command line.

As you edit a command line, at any point you can type regular characters to add those characters to the command line. The characters appear at the location of your cursor. You can use right ( ® ) and left ( ¬ ) arrows to move the cursor from one end to the other on the command line. You can also press the up ( ­ ) and down ( ¯ ) arrow keys to step through previous commands in the history list to select a command line for editing. (See the “Command line recall” section for details on how to recall commands from the history list.)

There are many keystrokes you can use to edit your command lines. Table 4-1 lists the keystrokes that you can use to move around the command line.

Table 4-1: Keystrokes for Navigating Command Lines

Keystroke

Full Name

Meaning

Ctrl+f

Character forward

Go forward one character.

Ctrl+b

Character backward

Go backward one character.

Alt+f

Word forward

Go forward one word.

Alt+b

Word backward

Go backward one word.

Ctrl+a

Beginning of line

Go to the beginning of the current line.

Ctrl+e

End of line

Go to the end of the line.

Ctrl+l

Clear screen

Clear screen and leave line at the top of the screen.

Table 4-2 lists the keystrokes for editing command lines.

Table 4-2: Keystrokes for Editing Command Lines

Keystroke

Full Name

Meaning

Ctrl+d

Delete current

Delete the current character.

Backspace or Rubout

Delete previous

Delete the previous character.

Ctrl+t

Transpose character

Switch positions of current and previous characters.

Alt+t

Transpose words

Switch positions of current and previous characters.

Alt+u

Uppercase word

Change the current word to uppercase.

Alt+l

Lowercase word

Change the current word to lowercase.

Alt+c

Capitalize word

Change the current word to an initial capital

Ctrl+v

Insert special character

Add a special character. For example, to add a Tab character, press Ctrl+v+Tab.

Table 4-3 lists the keystrokes for cutting and pasting text on a command line.

Table 4-3: Keystrokes for Cutting and Pasting Text in Command Lines

Keystroke

Full Name

Meaning

Ctrl+k

Cut end of line

Cut text to the end of the line.

Ctrl+u

Cut beginning of line

Cut text to the beginning of the line.

Ctrl+w

Cut previous word

Cut the word located behind the cursor.

Alt+d

Cut next word

Cut the word following the cursor.

Ctrl+y

Paste recent text

Paste most recently cut text.

Alt+y

Paste earlier text

Rotate back to previously cut text and paste it.

Ctrl+c

Delete whole line

Delete the entire line.

Command line completion

To save you a few keystrokes, the bash shell offers several different ways of completing partially typed values. To attempt to complete a value, type the first few characters, and then press Tab. Here are some of the values you can type partially:

  • Environment variable — If the text begins with a dollar sign ($), the shell completes the text with an environment variable from the current shell.

  • User name — If the text begins with a tilde (~), the shell completes the text with a user name. (This is actually just a case of file or directory expansion. For example, ~chr might expand to ~chris/, which would identify the home directory /home/chris.)

  • Command, alias, or function — If the text begins with regular characters, the shell tries to complete the text with a command, alias, or function name.

  • Host name — If the text begins with an at (@) sign, the shell completes the text with a host name taken from the /etc/hosts file.

    Tip 

    To add host names from an additional file, you can set the HOSTFILE variable to the name of that file. The file must be in the same format as /etc/hosts.

Here are a few examples of command completion. (When you see <Tab>, it means to press the Tab key on your keyboard.) Type the following:

$ echo $OS<Tab> $ cd ~ro<Tab> $ fing<Tab>  $ cat /etc/fed<Tab> $ mail root@loc<Tab>  

The first example causes $OS to expand to the $OSTYPE variable. In the next example, ~ro expands to the root user’s home directory (~root/). Next, fing expands to the finger command. After that, /etc/fed expands to /etc/fedora-release, so you can see your current release of Fedora Core. Finally, the address of root@loc expands to computer name localhost.

Of course, there will be times when there are several possible completions for the string of characters you have entered. In that case, you can check the possible ways text can be expanded by pressing Esc+? (or by pressing Tab twice) at the point where you want to do completion. The following code shows the result you would get if you checked for possible completions on $P.

 $ echo $P<Esc+?> $PATH $PPID $PS1 $PS2 $PS4 $PWD  $ echo $P 

In this case, there are six possible variables that begin with $P. After possibilities are displayed, the original command line returns, ready for you to complete it as you choose. If text you are trying to complete is not preceded by a $, ~, or @, you can still try to complete the text with a variable, user name, or host name. Press the following to complete your text:

  • Alt+~ — Complete the text before this point as a user name.

  • Alt+$ — Complete the text before this point as a variable.

  • Alt+@ — Complete the text before this point as a host name.

  • Ctrl+x+~ — List possible user name text completions.

  • Ctrl+x+$ — List possible environment variable completions.

  • Ctrl+x+@ — List possible host name completions.

  • Ctrl+x+! — List possible command name completions.

    Note 

    You may find that only the Alt key on the left side of your keyboard works with the examples above.

Command line recall

After you type a command line, that entire command line is saved in your shell’s history list. The list is stored in a history file, from which any command can be recalled to run again. After it is recalled, you can modify the command line, as described earlier.

To view your history list, use the history command. Type the command without options or followed by a number to list that many of the most recent commands. For example:

 $ history 8  382 date   383 ls /usr/bin | sort -a | more   384 man sort   385 cd /usr/local/bin   386 man more   387 useradd -m /home/chris -u 101 chris   388 passwd chris   389 history 8 

A number precedes each command line in the list. There are several ways to run a command immediately from this list, including:

  • Run Command Number (!n) — Replace the n with the number of the command line, and the command line indicated is run. For example, to repeat the date command shown as command number 382 from the previous history listing, you could type the following:

     $ !382 date  Thu May 13 21:30:06 PDT 2004  
  • Run Previous Command (!!) — Runs the previous command line. So, to immediately run that same date command again, type the following:

    $ !! date  Thu May 13 21:30:39 PDT 2004 
  • Run Command Containing String (!?string?) — Runs the most recent command that contains a particular string of characters. So, for example, you could run the date comand again by just searching for part of that command line as follows:

     $ !?dat? date  Thu May 13 21:32:41 PDT 2004 

Instead of just running a history command line immediately, you can recall a particular line and edit it. You can use these keys to do that:

  • Step (Arrow Keys) — Press the up ( ­ ) and down ( ¯ ) arrow keys to step through each command line in your history list to arrive at the one you want. (Ctrl+p and Ctrl+n do the same functions, respectively.)

  • Reverse Incremental Search (Ctrl+r) — After you press these keys, you are asked to enter a search string to do a reverse search. As you type the string, a matching command line appears that you can run or edit.

  • Reverse Search (Alt+p) — After you press these keys, you are asked to enter a string to do a reverse search. Type a string and press Enter to see the most recent command line that includes that string.

  • Forward Search (Alt+n) — After you press these keys, you are asked to enter a string to do a forward search. Type a string, and press Enter to see the most recent command line that includes that string.

  • Beginning of History List (Alt+<) — Brings you to the first entry of the history list.

  • End of History List (Alt+>) — Brings you to the last entry of the history list.

Another way to work with your history list is to use the fc command. Type fc followed by a history line number, and that command line is opened in a text editor. Make the changes that you want. When you exit the editor, the command runs. You could also give a range of line numbers (for example, fc 100 105). All the commands open in your text editor, and then run one after the other when you exit the editor.

The history list is stored in the .bash_history file in your home directory. Up to 1000 history commands are stored for you by default.

Connecting and expanding commands

A truly powerful feature of the shell is the capability to redirect the input and output of commands to and from other commands and files. To allow commands to be strung together, the shell uses metacharacters. As noted earlier, a metacharacter is a typed character that has special meaning to the shell for connecting commands or requesting expansion.

Piping commands

The pipe (|) metacharacter connects the output from one command to the input of another command. This lets you have one command work on some data, then have the next command deal with the results. Here is an example of a command line that includes pipes:

 $ cat /etc/password | sort | less 

This command lists the contents of the /etc/password file and pipes the output to the sort command. The sort command takes the user names that begin each line of the /etc/password file, sorts them alphabetically, and pipes the output to the less command. The less command displays the output one page at a time, so that you can go through the output a line or a page at a time (press q to quit at the end of the output).

Pipes are an excellent illustration of how UNIX, the predecessor of Linux, was created as an operating system made up of building blocks. A standard practice in UNIX was to connect utilities in different ways to get different jobs done. For example, before the days of graphical word processors, users created plain-text files that included macros to indicate formatting. To see how the document really appeared, they would use a command such as the following:

 $ gunzip < /usr/share/man/man1/grep.1.gz | nroff -c -man | less  

In this example, the contents of the grep man page (grep.1.gz) are directed to the gunzip command to be unzipped. The output from gunzip is piped to the nroff command to format the man page using the manual macro (-man). The output is piped to the less command to display the output. Because the file being displayed is in plain text, you could have substituted any number of options to work with the text before displaying it. You could sort the contents, change or delete some of the content, or bring in text from other documents. The key is that, instead of all those features being in one program, you get results from piping and redirecting input and output between multiple commands.

Sequential commands

Sometimes you may want a sequence of commands to run, with one command completing before the next command begins. You can do this by typing several commands on the same command line and separating them with semicolons (;):

 $ date ; troff -me verylargedocument | lpr ; date  

In this example, I was formatting a huge document and wanted to know how long it would take. The first command (date) showed the date and time before the formatting started. The troff command formatted the document and then piped the output to the printer. When the formatting was done, the date and time was printed again (so I knew how long the troff command took to complete).

Background commands

Some commands can take a while to complete. Sometimes you may not want to tie up your shell waiting for a command to finish. In those cases, you can have the commands run in the background by using the ampersand (&).

Text formatting commands (such as nroff and troff, described earlier) are examples of commands that are often run in the background to format a large document. You also might want to create your own shell scripts that run in the background to check continuously for certain events to occur, such as the hard disk filling up or particular users logging in.

Here is an example of a command being run in the background:

 $ troff -me verylargedocument | lpr &  

There are other ways of managing background and foreground processes (described in the “Managing background and foreground processes” section).

Expanding commands

With command substitution, you can have the output of a command interpreted by the shell instead of by the command itself. In this way, you can have the standard output of a command become an argument for another command. The two forms of command substitution are $(command) or `command`.

The command in this case can include options, metacharacters, and arguments. Here is an example of using command substitution:

 $ vi $(find /home | grep xyzzy) 

In this command line, the command substitution is done before the vi command is run. First, the find command starts at the /home directory and prints out all files and directories below that point in the file system. This output is piped to the grep command, which filters out all files except for those that include the string xyzzy. Finally, the vi command opens all filenames for editing (one at a time) that include xyzzy.

This particular example might be useful if you knew that you wanted to edit a file for which you knew the name but not the location. As long as the string was uncommon, you could find and open every instance of a filename existing beneath a point you choose in the file system.

Expanding arithmetic expressions

There may be times when you want to pass arithmetic results to a command. There are two forms you can use to expand an arithmetic expression and pass it to the shell: $[expression] or $((expression)). Here is an example:

 $ echo "I am $[2004 - 1957] years old." I am 47 years old. 

In this example, the shell interprets the arithmetic expression first (2004 - 1957), and then passes that information to the echo command. The echo command displays the text, with the results of the arithmetic (47) inserted.

Expanding variables

Environment variables that store information within the shell can be expanded using the dollar sign ($) metacharacter. When you expand an environment variable on a command line, the value of the variable is printed instead of the variable name itself, as follows:

 $ ls -l $BASH -rwxr-xr-x 1 root root 625516 Dec 5 11:13 /bin/bash 

Using $BASH as an argument to ls -l causes a long listing of the bash command to be printed. For more information on shell environment variables, see the following section.

Using shell environment variables

Every active shell stores pieces of information that it needs to use in what are called environment variables. An environment variable can store things such as locations of configuration files, mailboxes, and path directories. They can also store values for your shell prompts, the size of your history list, and type of operating system.

To see the environment variables currently assigned to your shell, type the declare command. (It will probably fill more than one screen, so type declare | more.) You can refer to the value of any of those variables by preceding it with a dollar sign ($) and placing it anywhere on a command line. For example:

 $ echo $USER chris 

This command prints the value of the USER variable, which holds your user name (chris). Substitute any other variable name for USER to print its value instead.

Common shell environment variables

When you start a shell (by logging in or opening a Terminal window), a lot of environment variables are already set. Here are some variables that are either set when you use a bash shell or that can be set by you to use with different features.

  • BASH — Contains the full path name of the bash command. This is usually /bin/bash.

  • BASH_VERSION — A number of the current version of the bash command.

  • EUID — This is the effective user ID number of the current user. It is assigned when the shell starts, based on the user’s entry in the /etc/passwd file.

  • FCEDIT — If set, this variable indicates the text editor used by the fc command to edit history commands. If this variable isn’t set, the vi command is used.

  • HISTFILE — The location of your history file. It is typically located at $HOME/.bash_history.

  • HISTFILESIZE — The number of history entries that can be stored. After this number is reached, the oldest commands are discarded. The default value is 1000.

  • HISTCMD — This returns the number of the current command in the history list.

  • HOME — This is your home directory. It is your current working directory each time you log in or type the cd command with any options.

  • HOSTTYPE — A value that describes the computer architecture on which the Linux system is running. For Intel-compatible PCs, the value is i386, i486, i586, i686, or something like i386-linux. For AMD 64-bit machines, the value is x86_64.

  • MAIL — This is the location of your mailbox file. The file is typically your user name in the /var/spool/mail directory.

  • OLDPWD — The directory that was the working directory before you changed to the current working directory.

  • OSTYPE — A name identifying the current operating system. For Fedora, the OSTYPE value is either linux or linux-gnu, depending on the type of shell you are using (Bash can run on other operating systems as well.)

  • PATH — The colon-separated list of directories used to find commands that you type. The default value for regular users is:

    /usr/local/bin:/bin:/usr/bin:/usr/bin:/usr/X11R6/bin:/home/chris/bin 

    For the root user, the value also includes /sbin, /usr/sbin, and /usr/local/sbin.

  • PPID — The process ID of the command that started the current shell (for example, its parent process).

  • PROMPT_COMMAND — Can be set to a command name that is run each time before your shell prompt is displayed. Setting PROMPT_COMMAND=date lists the current date/time before the prompt appears.

  • PS1 — Sets the value of your shell prompt. There are many items that you can read into your prompt (date, time, user name, host name, and so on). Sometimes a command requires additional prompts, which you can set with the variables PS2, PS3, and so on. (Setting your prompt is described later in this chapter.)

  • PWD — This is the directory that is assigned as your current directory. This value changes each time you change directories using the cd command.

  • RANDOM — Accessing this variable causes a random number to be generated. The number is between 0 and 32767.

  • SECONDS — The number of seconds since the time the shell was started.

  • SHLVL — The number of shell levels associated with the current shell session. When you log in to the shell, the SHLVL is 1. Each time you start a new bash command (by, for example, using su to become a new user, or by simply typing bash), this number is incremented.

  • TMOUT — Can be set to a number representing the number of seconds the shell can be idle without receiving input. After the number of seconds is reached, the shell exits. This is a security feature that makes it less likely for unattended shells to be accessed by unauthorized people. (This must be set in the login shell for it to actually cause the shell to log out the user.)

  • UID — The user ID number assigned to your user name. The user ID number is stored in the /etc/password file.

Setting your own environment variables

Environment variables can provide a handy way of storing bits of information that you use often from the shell. You can create any variables that you want (avoiding those that are already in use) so that you can read in the values of those variables as you use the shell. (The bash man page lists variables already in use.)

To set an environment variable temporarily, you can simply type a variable name and assign it to a value. Here is an example:

 $ AB=/usr/dog/contagious/ringbearer/grind ; export AB 

This example causes a long directory path to be assigned to the AB variable. The export AB command says to export the value to the shell so that it can be propagated to other shells you may open. With AB set, you can go to the directory by typing the following:

 $ cd $AB  
Tip 

You may have noticed that environment variables shown here are in all caps. Though case does matter with these variables, setting them as uppercase is a convention, not a necessity. You could just as easily set a variable to xyz as to XYZ (they are not the same, but either will work).

The problem with setting environment variables in this way is that as soon as you exit the shell in which you set the variable, the setting is lost. To set variables more permanently, you should add variable settings to a bash configuration file, as described later in this section.

If you want to have other text right up against the output from an environment variable, you can surround the variable in braces. This protects the variable name from being misunderstood. For example, if you wanted to add a command name to the AB variable shown earlier, you could type the following:

 $ echo ${AB}/adventure /usr/dog/contagious/ringbearer/grind/adventure 

Remember that you must export the variable so that it can be picked up by other shell commands. You must add the export line to a shell configuration file for it to take effect the next time you log in. The export command is fairly flexible. Instead of running the export command after you set the variable, you could do it all in one step, as follows:

 $ export XYZ=/home/xyz/bin  

You can override the value of any environment variable. This can be temporary by simply typing the new value. Or you can add the new export line to your $HOME/.bashrc file. One useful variable to update is PATH. Here is an example:

 $ export PATH=$PATH:/home/xyz/bin  

In this example, I added the /home/xyz/bin directory to the PATH, a useful technique if you want to run a bunch of commands from a directory that is not normally in your PATH, without typing the full or relative path each time.

If you decide that you no longer want a variable to be set, you can use the unset command to erase its value. For example, you could type unset XYZ, which would cause XYZ to have no value set. (Remember to remove the export from the $HOME/.bashrc file — if you added it there — or it will return the next time you open a shell.)

Managing background and foreground processes

If you are using Linux over a network or from a dumb terminal (a monitor that allows only text input with no GUI support), your shell may be all that you have. You may be used to a windowing environment where you have a lot of programs active at the same time so that you can switch among them as needed. This shell thing can seem pretty limited.

Although the bash shell doesn’t include a GUI for running many programs, it does let you move active programs between the background and foreground. In this way, you can have a lot of stuff running, while selectively choosing the one you want to deal with at the moment.

There are several ways to place an active program in the background. One mentioned earlier is to add an ampersand (&) to the end of a command line. Another way is to use the at command to run commands in a way in which they are not connected to the shell. (See Chapter 12 for more information about the at command.)

To stop a running command and put it in the background, press Ctrl+z. After the command is stopped, you can either bring it to the foreground to run (the fg command) or start it running in the background (the bg command).

Starting background processes

If you have programs that you want to run while you continue to work in the shell, you can place the programs in the background. To place a program in the background at the time you run the program, type an ampersand (&) at the end of the command line. For example:

 $ find /usr > /tmp/allusrfiles &  

This command finds all files on your Linux system (starting from /usr), prints those filenames, and puts those names in the file /tmp/allusrfiles. The ampersand (&) runs that command line in the background. To check which commands you have running in the background, use the jobs command, as follows:

$ jobs  [1]  Stopped (tty output)  vi /tmp/myfile  [2]  Running        find /usr -print > /tmp/allusrfiles &  [3]  Running        nroff -man /usr/man2/* >/tmp/man2 &  [4]- Running        nroff -man /usr/man3/* >/tmp/man3 &  [5]+ Stopped        nroff -man /usr/man4/* >/tmp/man4 

The first job shows a text-editing command (vi) that I placed in the background and stopped by pressing Ctrl+z while I was editing. Job two shows the find command I just ran. Jobs three and four show nroff commands currently running in the background. Job five had been running in the shell (foreground) until I decided too many processes were running and pressed Ctrl+z to stop job five until a few processes had completed.

The plus sign (+) next to number 5 shows that it was most recently placed in the background. The minus sign (-) next to number 4 shows that it was placed in the background just before the most recent background job. Because job 1 requires terminal input, it cannot run in the background. As a result, it is Stopped (preventing terminal output or input) until it is brought to the foreground again.

Tip 

To see the process ID for the background job, add an -l option to the jobs command. If you type ps, you can use the process ID to figure out which command is for a particular background job.

Using foreground and background commands

Continuing with the example, you can bring any of the commands on the jobs list to the foreground. For example, to edit myfile again, type:

 $ fg %1  

As a result, the vi command opens again, with all text as it was when you stopped the vi job.

Caution 

Before you put a text processor, word processor, or similar program in the background, make sure you save your file. It's easy to forget you have a program in the background and you will lose your data if you log out or the computer reboots later on.

To refer to a background job (to cancel or bring it to the foreground), use a percent sign (%) followed by the job number. You can also use the following to refer to a background job:

  • % — A percent sign alone refers to the most recent command put into the background (indicated by the plus sign). This action brings the command to the foreground.

  • %string — Refers to a job where the command begins with a particular string of characters. The string must be unambiguous. (In other words, typing %vi when there are two vi commands in the background results in an error message.)

  • %?string — Refers to a job where the command line contains a string at any point. The string must be unambiguous or the match will fail.

  • %-- — Refers to the previous job stopped before the one most recently stopped.

If a command is stopped, you can start it running again in the background using the bg command. For example, take job number 5 from the jobs list in the previous example:

[5]+ Stopped      nroff -man man4/* >/tmp/man4 

Type the following:

 $ bg %5 

After that, the job runs in the background. Its jobs entry appears as follows:

[5]   Running       nroff -man man4/* >/tmp/man4 & 

Configuring your shell

You can tune your shell to help you work more efficiently. Your prompt can provide pertinent information each time you press Enter. You can set aliases to save your keystrokes and permanently set environment variables to suit your needs. To make each change occur when you start a shell, you can add this information to your shell configuration files.

Several configuration files support how your shell behaves. Some of the files are executed for every user and every shell. Others are specific to the user who creates the configuration file. Here are the files that are of interest to anyone using the bash shell in Linux:

  • /etc/profile — This file sets up user environment information for every user. It is executed when you first log in. This file provides values for your path, as well as setting environment variables for such things as the location of your mailbox and the size of your history files. Finally, /etc/profile gathers shell settings from configuration files in the /etc/profile.d directory.

  • /etc/bashrc — This file is executed for every user who runs the bash shell, each time a bash shell is opened. It sets the default prompt and may add one or more aliases. Values in this file can be overridden by information in each user’s ~/.bashrc file.

  • ~/.bash_profile — This file is used by each user to enter information that is specific to his own use of the shell. It is executed only once, when the user logs in. By default it sets a few environment variables and executes the user’s .bashrc file.

  • ~/.bashrc — This file contains the information that is specific to your bash shells. It is read when you log in and also each time you open a new bash shell. This is the best location to add environment variables and aliases so that your shell picks them up.

  • ~/.bash_logout — This file executes each time you log out (exit the last bash shell). By default, it simply clears your screen.

To change the /etc/profile or /etc/bashrc files, you must be the root user. Users can change the information in the $HOME/.bash_profile, $HOME/.bashrc, and $HOME/.bash_logout files in their own home directories.

The following sections provide ideas about items to add to your shell configuration files. In most cases, you add these values to the .bashrc file in your home directory. However, if you administer a system, you may want to set some of these values as defaults for all of your Linux system’s users.

Setting your prompt

Your prompt consists of a set of characters that appear each time the shell is ready to accept a command. The PS1 environment variable sets what the prompt contains. If your shell requires additional input, it uses the values of PS2, PS3, and PS4.

When your Fedora system is installed, your prompt is set to include the following information: your user name, your host name, and the base name of your current working directory. That information is surrounded by brackets and followed by a dollar sign (for regular users) or a pound sign (for the root user). Here’s an example of that prompt:

[chris@myhost bin]$ 

If you change directories, the bin name would change to the name of the new directory. Likewise, if you were to log in as a different user or to a different host, that information would change.

You can use several special characters (indicated by adding a backslash to a variety of letters) to include different information in your prompt. These can include your terminal number, the date, and the time, as well as other pieces of information. Here are some examples:

  • \! — Shows the current command history number. This includes all previous commands stored for your user name.

  • \# — Shows the command number of the current command. This includes only the commands for the active shell.

  • \$ — Shows the user prompt ($) or root prompt (#), depending on which user you are.

  • \W — Shows only the current working directory base name. For example, if the current working directory was /var/spool/mail, this value would simply appear as mail.

  • \[ — Precedes a sequence of nonprinting characters. This could be used to add a terminal control sequence into the prompt for such things as changing colors, adding blink effects, or making characters bold. (Your terminal determines the exact sequences available.)

  • \] — Follows a sequence of nonprinting characters.

  • \\ — Shows a backslash.

  • \d — Displays the day, month, and number of the date. For example: Sat Jan 23.

  • \h — Shows the host name of the computer running the shell.

  • \n — Causes a newline to occur.

  • \nnn — Shows the character that relates to the octal number replacing nnn.

  • \s — Displays the current shell name. For the bash shell, the value would be bash.

  • \t — Prints the current time in hours, minutes, and seconds (for example, 10:14:39).

  • \u — Prints your current user name.

  • \w — Displays the full path to the current working directory.

    Tip 

    If you are setting your prompt temporarily by typing at the shell, you should put the value of PS1 in quotes. For example, you could type export PS1="[\t \w]\$ " to see a prompt that looks like this: [20:26:32 /var/spool]$.

To make a change to your prompt permanent, add the value of PS1 to your .bashrc file in your home directory (assuming that you are using the bash shell). There may already be a PS1 value in that file that you can modify.

Adding environment variables

You may consider adding a few environment variables to your .bashrc file. These can help make working with the shell more efficient and effective:

  • TMOUT — This sets how long the shell can be inactive before bash automatically exits. The value is the number of seconds for which the shell has not received input. This can be a nice security feature, in case you leave your desk while you are still logged in to Linux. So as not to be logged you off while you are working, you may want to set the value to something like TMOUT=1800 (to allow 30 minutes of idle time).

  • PATH — As described earlier, the PATH variable sets the directories that are searched for commands you use. If you often use directories of commands that are not in your PATH, you can permanently add them. To do this, add a PATH variable to your .bashrc file. For example, to add a directory called /getstuff/bin, add the following:

    PATH=$PATH:/getstuff/bin ; export PATH 

    This example first reads all the current path directories into the new PATH ($PATH), adds the /getstuff/bin directory, and then exports the new PATH.

    Caution 

    Some people add the current directory to their PATH by adding a directory identified simply as a dot (.), as follows:

    PATH=.:$PATH ; export PATH 

    This lets you always run commands in your current directory (which people may be used to if they have used DOS). However, the security risk with this procedure is that you could be in a directory that contains a command that you don’t intend to run from that directory. For example, a hacker could put an ls command in a directory that, instead of listing the content of your directory, does something devious.

  • WHATEVER — You can create your own environment variables to provide shortcuts in your work. Choose any name that is not being used and assign a useful value to it. For example, if you do a lot of work with files in the /work/time/files/info/memos directory, you could set the following variable:

    M=/work/time/files/info/memos ; export M 

    You could make that your current directory by typing cd $M. You could run a program from that directory called hotdog by typing $M/hotdog. You could edit a file from there called bun by typing vi $M/bun.

Adding aliases

Setting aliases can save you even more typing than setting environment variables. With aliases, you can have a string of characters execute an entire command line. You can add and list aliases with the alias command. Here are some examples:

alias p=’pwd ; ls -CF’  alias rm=’rm -i’ 

In the first example, the letter p is assigned to run the command pwd, and then to run ls -CF to print the current working directory and list its contents in column form. The second runs the rm command with the -i option each time you simply type rm. (This is an alias that is often set automatically for the root user, so that instead of just removing files, you are prompted for each individual file removal. This prevents you from removing all the files in a directory by mistakenly typing something such as rm *.)

While you are in the shell, you can check which aliases are set by typing the alias command. If you want to remove an alias, you can type unalias. (Remember that if the alias is set in a configuration file, it will be set again when you open another shell.)




Red Hat Fedora Linux 3 Bible
Red Hat Fedora Linux 3 Bible
ISBN: 0764578723
EAN: 2147483647
Year: 2005
Pages: 286

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net