Chapter 3: Basic Shell Features

8

3.2 Shell Commands

A simple shell command such as echo a b c consists of the command itself followed by arguments, separated by spaces.

More complex shell commands are composed of simple commands arranged together in a variety of ways: in a pipeline in which the output of one command becomes the input of a second, in a loop or conditional construct, or in some other grouping.

3.2.1 Simple Commands

A simple command is the kind of command encountered most often. It’s just a sequence of words separated by blanks, terminated by one of the shell’s control operators (see Chapter 2

[Definitions], page 3). The first word generally specifies a command to be executed, with the rest of the words being that command’s arguments.

The return status (see Section 3.7.5 [Exit Status], page 38) of a simple command is its exit status as provided by the posix 1003.1 waitpid function, or 128+n if the command was terminated by signal n.

3.2.2 Pipelines

A pipeline is a sequence of simple commands separated by one of the control operators

‘|’ or ‘|&’.

The format for a pipeline is

[time [-p]] [!] command1 [ | or |& command2 ] ...

The output of each command in the pipeline is connected via a pipe to the input of the next command. That is, each command reads the previous command’s output. This connection is performed before any redirections specified by the command.

If ‘|&’ is used, command1’s standard error, in addition to its standard output, is con- nected to command2’s standard input through the pipe; it is shorthand for 2>&1 |. This implicit redirection of the standard error to the standard output is performed after any redirections specified by the command.

The reserved word time causes timing statistics to be printed for the pipeline once it finishes. The statistics currently consist of elapsed (wall-clock) time and user and system time consumed by the command’s execution. The -p option changes the output format to that specified by posix. When the shell is in posix mode (see Section 6.11 [Bash POSIX

Mode], page 94), it does not recognize time as a reserved word if the next token begins with a ‘-’. The TIMEFORMAT variable may be set to a format string that specifies how the timing information should be displayed. See Section 5.2 [Bash Variables], page 69, for a description of the available formats. The use of time as a reserved word permits the timing of shell builtins, shell functions, and pipelines. An external time command cannot time these easily.

When the shell is in posix mode (see Section 6.11 [Bash POSIX Mode], page 94), time may be followed by a newline. In this case, the shell displays the total user and system time consumed by the shell and its children. The TIMEFORMAT variable may be used to specify the format of the time information.

If the pipeline is not executed asynchronously (see Section 3.2.3 [Lists], page 9), the shell waits for all commands in the pipeline to complete.