Previous Section  < Day Day Up >  Next Section

13.3. The Command Line

After you log on, the bash shell displays its primary prompt, a dollar sign by default. The shell is your command interpreter. When the shell is running interactively, it reads commands from the terminal and breaks the command line into words. A command line consists of one or more words (or tokens), separated by whitespace (blanks and/or tabs), and terminated with a newline, generated by pressing the Enter key. The first word is the command, and subsequent words are the command's arguments. The command may be a UNIX/Linux executable program such as ls or date, a user-defined function, a built-in command such as cd or pwd, or a shell script. The command may contain special characters, called metacharacters, which the shell must interpret while parsing the command line. If a command line is too long, the backslash character, followed by a newline, will allow you to continue typing on the next line. The secondary prompt will appear until the command line is terminated.

13.3.1 The Order of Processing Commands

The first word on the command line is the command to be executed. The command may be a keyword, an alias, a function, a special built-in command or utility, an executable program, or a shell script. The command is executed according to its type in the following order:

  1. Aliases

  2. Keywords (such as if, function, while, until)

  3. Functions

  4. Built-in commands

  5. Executables and scripts

Special built-in commands and functions are defined within the shell, and therefore are executed from within the context of the current shell, making them much faster in execution. Scripts and executable programs such as ls and date are stored on disk, and the shell, in order to execute them, must first locate them within the directory hierarchy by searching the PATH environment variable; the shell then forks a new shell that executes the script. To find out the type of command you are using—that is, a built-in command, an alias, a function, or an executable—use the built-in type command. (See Example 13.18.)

Example 13.18.

$ type pwd

pwd is a shell builtin

$ type test

test is a shell builtin

$ type clear

clear is /usr/bin/clear

$ type m

m is aliased to 'more'

$ type bc

bc is /usr/bin/bc

$ type if

if is a shell keyword

$ type -path cal

/usr/bin/cal

$ type which

which is aliased to 'type -path'

$ type greetings

greetings is a function

greetings ()

{

       echo "Welcome to my world!";

}


13.3.2 Built-In Commands and the help Command

Built-in commands are commands that are part of the internal source code for the shell. They are built-in and readily available to the shell, whereas commands such as date, cal, and finger are compiled binary programs that reside on the disk. There is less overhead in executing a built-in because it involves no disk operations. Built-in commands are executed by the shell before executable programs on disk. Bash has added a new online help system so that you can see all the built-ins, or a description for a particular built-in; help itself is a built-in command. See Table 13.28 on page 857 for a complete list of built-in commands.

Example 13.19.

1   $ help help

    help: help [pattern ...]

    Display helpful information about built-in commands. if PATTERN

    is specified, gives detailed help on all commands matching

    PATTERN, otherwise a list of the built-ins is printed.

2   $ help pw

    pwd: pwd

        Print the current working directory.


Table 13.28. Built-In Commands

Command

What It Does

:

Do-nothing command; returns exit status zero.

.

Executes program in context of current process; same as source.

. file

The dot command reads and executes command from file.

break

Breaks out of the innermost loop.

break [n]

See "The break Command" on page 919.

alias

Lists and creates "nicknames" for existing commands.

bg

Puts a job in the background.

bind

Display current key and function bindings, or binds keys to a readline function or macro.

builtin [sh–builtin [args]]

Runs a shell built-in, passing it args and returning zero exit status. Useful if a function and built-in have the same name.

cd [arg]

Changes the directory to home if no arg or to value of arg.

command command [arg]

Runs a command even if a function has the same name; i.e., bypasses function lookup.

continue [n]

See "The continue Command" on page 920.

declare [var]

Displays all variables or declares variables with optional attributes.

dirs

Displays a list of currently remembered directories resulting from pushd.

disown

Removes an active job from the job table.

echo [args]

Displays args terminated with a newline.

enable

Enables and disables shell built-in commands.

eval [args]

Reads args as input to the shell and executes the resulting command(s).

exec command

Runs command in place of this shell.

exit [n]

Exits the shell with status n.

export [var]

Makes var known to subshells.

fc

History's fix command for editing history commands.

fg

Puts background job into foreground.

getopts

Parses and processes command-line options.

hash

Controls the internal hash table for quicker searches for commands.

help [command]

Displays helpful info about built-in commands and, if command is specified, detailed help about that built-in command.

history

Displays the history list with line numbers.

jobs

Lists jobs put in the background.

kill [–signal process ]

Sends the signal to the PID number or job number of the process. Type at the prompt: kill –l.

getopts

Used in shell scripts to parse command line and check for legal options.

let

Used for evaluating arithmetic expressions and assigning results of arithmetic calculations to variables.

local

Used in functions to restrict the scope of variables to the function.

logout

Exits the login shell.

popd

Removes entries from the directory stack.

pushd

Adds entries to the directory stack.

pwd

Prints present working directory.

read [var]

Reads line from standard input into variable var.

readonly [var]

Makes variable var read-only. Cannot be reset.

return [n]

Returns from a function where n is the exit value given to the return.

set

Sets options and positional parameters. See "The set Command and Positional Parameters" on page 876.

shift [n]

Shifts positional parameters to the left n times.

stop pid

Halts execution of the process number PID.

suspend

Stops execution of the current shell (but not if a login shell).

test

Checks file types and evaluates conditional expressions.

times

Prints accumulated user and system times for processes run from this shell.

trap [arg] [n]

When shell receives signal n ( 0, 1, 2, or 15 ), executes arg.

type [command]

Prints the type of command (e.g., pwd is a built-in shell command).

typeset

Same as declare. Sets variables and gives them attributes.

ulimit

Diplays and sets process resource limits.

umask [octal digits]

Sets user file creation mode mask for owner, group, and others.

unalias

Unsets aliases.

unset [name]

Unset value of variable or function.

wait [pid#n]

Waits for background process with PID number n and reports termination status.


13.3.3 Changing the Order of Command-Line Processing

Bash provides three built-in commands that can override the order of command-line processing: command, builtin, and enable.

The command built-in eliminates aliases and functions from being looked up in the order of processing. Only built-ins and executables, found in the search path, will be processed.

The builtin command looks up only built-ins, ignoring functions and executables found in the path.

The enable built-in command turns built-ins on and off. By default, built-ins are enabled. Disabling a built-in allows an executable command to be executed without specifying a full pathname, even if it has the same name as a built-in. (In normal processing, bash searches for built-ins before disk executable commands.) Built-ins become disabled by using the –n switch. For example, a classic confusion for new shell programmers is naming a script test. Because test is a built-in command, the shell will try to execute it rather than the user's script (because a built-in is normally executed before any executable program). By typing: enable –n test, the test built-in is disabled, and the user's script will take precedence.

Without options, the enable built-in prints a list of all the built-ins. Each of the following built-ins are described in "Shell Built-In Commands" on page 857.

Example 13.20.

1   $ enable

    enable .

    enable :

    enable [

    enable alias

    enable bg

    enable bind

    enable break

    enable builtin

    enable cd

    enable command

    enable continue

    enable declare

    enable dirs

        .....

    enable read

    enable readonly

    enable return

    enable set

    enable shift

    enable shopt

       .....

    enable type

    enable typeset

    enable ulimit

    enable umask

    enable unalias

    enable unset

    enable wait



2   enable -n test



3   function cd { builtin cd; echo $PWD; }


EXPLANATION

  1. The enable built-in, without any options, displays a complete list of all bash shell built-in commands. This example shows just part of that list.

  2. With the –n switch, the test built-in command is disabled. Now, you execute your script named test without worrying about the built-in test being executed instead. It's not good practice to name a script by the same name as an operating system command, because if you try to run the same script in another shell, the disabling of built-ins doesn't exist.

  3. The function is called cd. The builtin command causes the cd within the function definition to be called instead of the function cd, which would cause an endless recursive loop.

13.3.4 The Exit Status

After a command or program terminates, it returns an exit status to the parent process. The exit status is a number between 0 and 255. By convention, when a program exits, if the status returned is 0, the command was successful in its execution. When the exit status is nonzero, the command failed in some way. If a command is not found by the shell, the exit status returned is 127. If a fatal signal causes the command to terminate, the exit status is 128 plus the value of the signal that caused it to die.

The shell status variable, ?, is set to the value of the exit status of the last command that was executed. Success or failure of a program is determined by the programmer who wrote the program.

Example 13.21.

1   $ grep ellie /etc/passwd

    ellie:MrHJEFd2YpkJY:501:501::/home/ellie:/bin/bash

2   $ echo $?

    0



3   $ grep nicky /etc/passwd

4   $ echo $?

    1



5   $ grep ellie /junk

    grep: /junk: No such file or directory

6   $ echo $?

    2



7   $ grip ellie /etc/passwd

    bash: grip: command not found

8   $ echo $?

    127



9   $ find / -name core ^C    # User presses Ctrl-C

10  $ echo $?

    130


EXPLANATION

  1. The grep program searches for the pattern ellie in the /etc/passwd file and is successful. The line from /etc/passwd is displayed.

  2. The ? variable is set to the exit value of the grep command. Zero indicates successful status.

  3. The grep program cannot find user nicky in the /etc/passwd file.

  4. The grep program cannot find the pattern; the ? variable return value is nonzero. An exit status of 1 indicates failure.

  5. The grep fails because the /junk file cannot be opened.The grep error message is sent to standard error, the screen.

  6. If grep cannot find the file, it returns an exit status of 2.

  7. The grip command is not found by the shell.

  8. Because the command is not found, the exit status, 127, is returned.

  9. The find command is interrupted when the SIGINT signal is sent by pressing Ctrl-C. The signal number for Ctrl-C is 2.

  10. The status returned from a process that has been killed is 128 + the number of the signal (i.e., 128 + 2).

13.3.5 Multiple Commands at the Command Line

A command line can consist of multiple commands. Each command is separated by a semicolon, and the command line is terminated with a newline. The exit status is that of the last command in the chain of commands.

Example 13.22.

$ ls; pwd; date


EXPLANATION

The commands are executed from left to right, one after the other, until the newline is reached.

13.3.6 Command Grouping

Commands may also be grouped so that all of the output is either piped to another command or redirected to a file.

Example 13.23.

$ ( ls; pwd; date ) > outputfile


EXPLANATION

The output of each of the commands is sent to the file called outputfile. The spaces inside the parentheses are necessary.

13.3.7 Conditional Execution of Commands

With conditional execution, two command strings are separated by the special metacharacters, double ampersands (&&) and double vertical bars (||). The command on the right of either of these metacharacters will or will not be executed based on the exit condition of the command on the left.

Example 13.24.

$ cc prgm1.c –o prgm1 && prgm1


EXPLANATION

If the first command is successful (has a 0 exit status), the command after the && is executed; that is, if the cc program can successfully compile prgm1.c, the resulting executable program, prgm1, will be executed.

Example 13.25.

$ cc prog.c >& err || mail bob < err


EXPLANATION

If the first command fails (has a nonzero exit status), the command after the || is executed; that is, if the cc program cannot compile prog.c, the errors are sent to a file called err, and user bob will be mailed the err file.

13.3.8 Commands in the Background

Normally, when you execute a command, it runs in the foreground, and the prompt does not reappear until the command has completed execution. It is not always convenient to wait for the command to complete. When you place an ampersand (&) at the end of the command line, the shell will return the shell prompt immediately and execute the command in the background concurrently. You do not have to wait for one command to finish before starting another. The output from a background job will be sent to the screen as it processes. Therefore, if you intend to run a command in the background, the output of that command might be redirected to a file or piped to another device, such as a printer, so that its output does not interfere with the more recent command that was typed.

The ! variable contains the PID number of the last job put in the background. (See the following section, "Job Control," for more on background processing.)

Example 13.26.

1   $ man sh | lp&

2   [1] 1557

3   $ kill -9 $!


EXPLANATION

  1. The output of the man command (the manual pages for the UNIX command) is piped to the printer. The ampersand at the end of the command line puts the job in the background.

  2. There are two numbers that appear on the screen: the number in square brackets indicates that this is the first job to be placed in the background; the second number is the PID, or the process identification number of this job.

  3. The shell prompt appears immediately. While your program is running in the background, the shell is waiting for another command in the foreground. The ! variable evaluates to the PID of the job most recently put in the background. If you get it in time, you will kill this job before it goes to the print queue.

    Previous Section  < Day Day Up >  Next Section