Previous Section  < Day Day Up >  Next Section

11.3. The Command Line

After logging in, the Korn shell displays its primary prompt. 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 Enter. The first word is the command, and subsequent words are the command's arguments. The command may be a UNIX executable program such as ls or pwd, a built-in command such as cd or jobs, 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.

11.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, a special built-in command or utility, a function, a script, or an executable program. The command is executed according to its type in the following order:[1]

[1] A built-in command will override a function; therefore, an alias must be defined to the name of the function. (See "Aliases" on page 604.) In the 1994 version of the Korn shell, the order of processing functions and built-ins was reversed, thus alleviating this problem.

  1. Keywords (such as if, while, until)

  2. Aliases (see typeset –f)

  3. Built-in commands

  4. Functions

  5. Scripts and executables

The special built-in commands and functions are defined within the shell, and therefore are executed from within the current shell, making them much faster in execution. Scripts and executable programs such as ls and pwd are stored on disk, and the shell must 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, use the built-in command, whence –v , or its alias, type. (See Example 11.9.)

Example 11.9.

$ type print

print is a shell builtin

$ type test

test is a shell builtin

$ type ls

ls is a tracked alias for /usr/bin/ls

$ type type

type is an exported alias for whence -v

$ type bc

bc is /usr/bin/bc

$ type if

if is a keyword


11.3.2 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. The Korn 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. In shell scripts, you can explicitly control the exit status by using the exit command.

Example 11.10.

1   $ grep "ellie" /etc/passwd

    ellie:GgMyBsSJavd16s:9496:40:Ellie Quigley:/home/jody/ellie

2   $ echo $?

    0



3   $ grep "nicky" /etc/passwd

4   $ echo $?

    1



5   $ grep "scott" /etc/passsswd

    grep: /etc/passsswd: No such file or directory

6   $ echo $?

    2


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 success.

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

  4. If the grep program cannot find the pattern, it returns an exit status of 1.

  5. The grep fails because the file /etc/passsswd cannot be opened.

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

11.3.3 Multiple Commands and Command Grouping

A command line can consist of multiple commands. Each command is separated by a semicolon, and the command line is terminated with a newline.

Example 11.11.

$ ls; pwd; date


EXPLANATION

The commands are executed from left to right until the newline is reached. Commands may also be grouped so that all of the output is either piped to another command or redirected to a file.

Example 11.12.

$ ( ls ; pwd; date ) > outputfile


EXPLANATION

The output of each of the commands is sent to the file called outputfile.

11.3.4 Conditional Execution of Commands

With conditional execution, two command strings are separated by two special metacharacters, && and ||. 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 11.13.

$ cc prgm1.c –o prgm1 && prgm1


EXPLANATION

If the first command is successful (has a 0 exit status), the command after the && is executed.

Example 11.14.

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


EXPLANATION

If the first command fails (has a nonzero exit status), the command after the || is executed.

11.3.5 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. By placing 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 to start up another command. 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 should be redirected to a file or piped to another device such as a printer so that the output does not interfere with what you are doing.

Example 11.15.

1   $ man ksh | lp&

2   [1] 1557

3   $


EXPLANATION

  1. The output of the manual pages for the Korn shell is piped to the printer. The ampersand at the end of the command line puts the job in the background.

  2. Two numbers 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, the process identification number, of this job.

  3. The Korn shell prompt appears immediately. While your program is running in the background, the shell is waiting for another command in the foreground.

11.3.6 Command-Line History

The history mechanism keeps a numbered record of the commands that you have typed at the command line in a history file. You can recall a command from the history file and re-execute it without retyping the command. The history built-in command displays the history list. The default name for the history file is .sh_history, and it is located in your home directory.

The HISTSIZE variable, accessed when ksh first accesses the history file, specifies how many commands can be accessed from the history file. The default size is 128. The HISTFILE variable specifies the name of the command history file (~/.sh_history is the default) where commands are stored. The history file grows from one login session to the next; it becomes very large unless you clean it out. The history command is a preset alias for the fc –l command.

Example 11.16.

(The ~/sh_history File)

(This file contains a list of the commands the user has typed at the command line)



    netscape&

    ls

    mkdir javascript

    cd javascript

    &cp ../javapdf.zip .

    gunzip javapdf.zip

    unzip javapdf.zip

    ls

    more chapter10*

    ls -l

    rm chapter9.pdf

    ls

    ls -l



    ... continues ...



1   $ history –1 –5        # List last 5 commands, preceding this one in reversed order.

    13  history –3

    12  history 8

    11  history –n

    10  history

    9   set

2   $ history –5 –1         # Print last 5 commands, preceding this one in order.

    10   history

    11   history -n

    12   history 8

    13   history -3

    14   history –1 –5

3   $ history                # (Different history list)

    78   date

    79   ls

    80   who

    81   echo hi

    82   history

4   $ history ls echo        # Display from most recent ls command to

    79   ls                  # most recent echo command.

    80   who

    81   echo hi

5   $ history –r ls echo      # –r reverses the list

    81   echo hi

    80   who

    79    ls


The history Command/Redisplay Commands

The built-in history command lists previously typed commands preceded by a number. The command can take arguments to control the display.

Example 11.17.

1   $ history            # Same as fc –l

    1 ls

    2 vi file1\

    3 df

    4 ps –eaf

    5 history

    6 more /etc/passwd

    7 cd

    8 echo $USER

    9 set

    10 history

2   $ history –n         # Print without line numbers

    ls

    vi file1

    df

    ps –eaf

    history

    more /etc/passwd

    cd

    echo $USER

    set

    history

    history –n

3   $ history 8          # List from 8th command to present

    8    echo $USER

    9    set

    10   history

    11   history –n

    12   history 8

4   $ history –3         # List this command and the 3 preceding it

    10   history

    11   history –n

    12   history 8

    13   history –3

5   $ history –1 –5       # List last 5 commands, preceding this one in reversed order.

    13   history –3

    12   history 8

    11   history –n

    10   history

    9    set

6   $ history –5 –1       # Print last 5 commands, preceding this one in order.

    10   history

    11   history -n

    12   history 8

    13   history -3

    14   history –1 –5

7   $ history             # (Different history list)

    78   date

    79   ls

    80   who

    81   echo hi

    82   history


Re-executing Commands with the r Command

The r command redoes the last command typed at the command line. If the r command is followed by a space and a number, the command at that number is re-executed. If the r command is followed by a space and a letter, the last command that began with that letter is executed. Without any arguments, the r command re-executes the most previous command on the history list.

Example 11.18.

1   $ r date

    date

    Mon May 15 12:27:35 PST 2004

2   $ r 3    redo command number 3

    df

    Filesystem   kbytes     used      avail     capacity    Mounted on

    /dev/sd0a    7735       6282      680       90%         /

    /dev/sd0g    144613     131183    0         101%        /usr

    /dev/sd2c    388998     211395    138704    60%         /home.

3   $ r vi         # Redo the last command that began with pattern vi.

4   $ r vi file1=file2    # Redo last command that began with vi and substitute the

                           # first occurrence of file1 with file2.


EXPLANATION

  1. The last command, date, is re-executed.

  2. The third command in the history file is executed.

  3. The last command, starting with the string vi, is executed.

  4. The string file1 is replaced with the string file2. The last command, vi file1, is replaced with vi file2.

11.3.7 Command-Line Editing

The Korn shell provides two built-in editors, emacs and vi, that allow you to interactively edit your history list. To enable the vi editor, add the set command listed below and put this line in your .profile file. The emacs built-in editor works on lines in the history file one line at a time, whereas the vi built-in editor works on commands consisting of more than one line. To set vi, type

set –o vi

or

VISUAL=vi

or

EDITOR=/usr/bin/vi


If using emacs, type

set –o emacs

or

VISUAL=emacs

or

EDITOR=/usr/bin/emacs


Note that set –o vi overrides VISUAL, and VISUAL overrides EDITOR.

The vi Built-In Editor

To edit the history list, press the Esc key and use the standard keys that you would use in vi for moving up and down, left and right, deleting, inserting, and changing text. See Table 11.2. After making the edit, press the Enter key. The command will be executed and added to the bottom of the history list. To scroll upward in the history file, press the Esc key and then the K key.

Table 11.2. vi Commands

Command

Function

Moving Through the History File

Esc k or +

Move up the history list

Esc j or –

Move down the history list

Esc G

Move to first line in history file

Esc 5G

Move to fifth command in history file for string

/string

Search upward through history file

?

String search downward through history file

Moving Around on a Line (Press the Esc Key First)

h

Move left on a line

l

Move right on a line

b

Move backward a word

e or w

Move forward a word

^ or 0

Move to beginning of first character on the line

$

Move to end of line

Editing with vi

a A

Append text

i I

Insert text

dd dw x

Delete text into a buffer (line, word, or character)

cc C

Change text

u U

Undo

yy Y

Yank (copy a line into buffer)

p P

Put yanked or deleted line down below or above the line

r R

Replace a letter or any amount of text on a line


The emacs Built-In Editor

To start moving backward through the history file, press ^P. To move forward, press ^N. Use emacs editing commands to change or correct text, then press Enter and the command will be re-executed. See Table 11.3.

Table 11.3. emacs Commands

Command

Function

Moving Through the History File

Ctrl-P

Move up history file

Ctrl-N

Move down history file

Ctrl-B

Move backward one character

Ctrl-R

Search backward for string

Esc B

Move back one word

Ctrl-F

Move forward one character

Esc F

Move forward one word

Ctrl-A

Move to the beginning of the line

Ctrl-E

Move to the end of the line

Esc <

Move to the first line of the history file

Esc >

Move to the last line of the history file

Editing with emacs

Ctrl-U

Delete the line

Ctrl-Y

Put the line back

Ctrl-K

Delete from cursor to the end line

Ctrl-D

Delete a letter

Esc D

Delete one word forward

Esc H

Delete one word backward

Esc space

Set a mark at cursor position

Ctrl-X Ctrl-X

Exchange cursor and mark

Ctrl-P Ctrl-Y

Push region from cursor to mark into a buffer (Ctrl-P) and put it down (Ctrl-Y)


FCEDIT and Editing Commands

The fc command is a built-in command that can be used with the FCEDIT [2] variable (typically set in the .profile file) to invoke the editor of your choice for editing the history file. This can be any editor on your system. The FCEDIT variable is set to the full pathname of your favorite editor. If FCEDIT is not set, the default editor, /bin/ed, is invoked when you type the fc command.

[2] On versions of the Korn shell newer than 1988, the FCEDIT variable has been renamed HISTEDIT, and the fc command has been renamed hist.

The FCEDIT variable should be set to the chosen editor. You can specify a number of items from the history list that you want to edit. After you edit the commands, the Korn shell will execute the whole file. Any commands that are preceded by a pound sign (#) will be treated as comments and will not be executed. See Table 11.4 on page 603 for more on commenting and filename expansion.

Example 11.19.

1   $ FCEDIT=/usr/bin/vi

2   $ pwd

3   $ fc

<Starts up the full-screen vi editor with the pwd command on line 1>



           



4   $ history

    1 date

    2 ls -l

    3 echo "hello"

    4 pwd



5   $ fc -3 -1       # Start vi, edit, write/quit, and execute last 3 commands.


Table 11.4. Using the Esc Key and Filename Expansion

Combination

Result

command [Esc]#

# precedes command with a #; puts it on the history list commented; command will not be executed.

command [Esc]_

Underscore inserts the last word of the last command at the cursor.

command [Esc] 2_

Inserts the second word of the last command at the cursor position.

word[Esc] *

* replaces the current word with all files matched.

word[Esc] \

\ replaces the current word with the first filename that starts with the same characters; filename expansion.

word[Esc]=

Displays all filenames beginning with the same character as the current word and displays them in a numbered list.


EXPLANATION

  1. The FCEDIT variable can be assigned the pathname for any of the UNIX text editors you have on your system, such as vi, emacs, textedit, and so on. If not set, the ed editor is the default.

  2. The pwd command is typed at the command line. It will be placed in the history file.

  3. The fc command caused the editor (set in FCEDIT) to be invoked with the last command typed in the editor window. If the user writes and quits the editor, any commands typed there will be executed.

  4. The history command lists recently typed commands.

  5. The fc command is used to start up the editor with the last three commands from the history file in the editor's buffer.

    Previous Section  < Day Day Up >  Next Section