Section 6.11. Built-in Commands (Bash and Korn Shells)


6.11. Built-in Commands (Bash and Korn Shells)

Examples to be entered as a command line are shown with the $ prompt. Otherwise, examples should be treated as code fragments that might be included in a shell script. For convenience, some of the reserved words used by multiline commands are also included.

!

     ! pipeline 

Not ksh88. Negate the sense of a pipeline. Returns an exit status of 0 if the pipeline exited nonzero, and an exit status of 1 if the pipeline exited zero. Typically used in if and while statements.

Example

This code prints a message if user jane is not logged on:

     if ! who | grep jane > /dev/null     then             echo jane is not currently logged on     fi 

#

     # 

Ignore all text that follows on the same line. # is used in shell scripts as the comment character and is not really a command.

#!shell

     #!shell [option] 

Used as the first line of a script to invoke the named shell. Anything given on the rest of the line is passed as a single argument to the named shell. This feature is typically implemented by the kernel, but may not be supported on some older systems. Some systems have a limit of approximately 32 characters on the maximum length of shell. For example:

     #!/bin/sh 

:

     : 

Null command. Returns an exit status of 0. The line is still processed for side effects, such as variable and command substitutions, or I/O redirection. See the following Example and the Example under case.

Example

Check whether someone is logged in:

     if who | grep $1 > /dev/null     then :   # Do nothing if user is found     else echo "User $1 is not logged in"     fi 

.

     . file [arguments] 

Read and execute lines in file. file does not have to be executable, but must reside in a directory searched by PATH. The arguments are stored in the positional parameters. If Bash is not in POSIX mode and file is not found in PATH, it will look in the current directory for file.

[[ ]]

     [[ expression ]] 

Same as test expression or [ expression ], except that [[ ]] allows additional operators. Word splitting and filename expansion are disabled. Note that the brackets ([ ]) are typed literally and that they must be surrounded by whitespace.

Additional Operators


&&

Logical AND of test expressions (short circuit).


||

Logical OR of test expressions (short circuit).


<

First string is lexically "less than" the second.


>

First string is lexically "greater than" the second.

alias

     alias [options] [name[='cmd']] 

Assign a shorthand name as a synonym for cmd. If ='cmd' is omitted, print the alias for name ; if name is also omitted, print all aliases. If the alias value contains a trailing space, the next word on the command line also becomes a candidate for alias expansion. See also unalias.

These aliases are built into ksh88. Some use names of existing Bourne shell or C shell commands:

     autoload='typeset -fu'     false='let 0'     functions='typeset -f'     hash='alias -t'     history='fc -l'     integer='typeset -i'     nohup='nohup '     r='fc -e -'     true=':'     type='whence -v' 

The following aliases are built into ksh93:

     autoload='typeset -fu'     command='command '     fc='hist'     float='typeset -E'     functions='typeset -f'     hash='alias -t --'     history='hist -l'     integer='typeset -i'     nameref='typeset -n'     nohup='nohup '     r='hist -s'     redirect='command exec'     stop='kill -s STOP'     times='{ {time;} 2>&1;}'     type='whence -v' 

Options


-p

Print the word alias before each alias. Not ksh88.


-t

Create a tracked alias for a Unix command name. The Korn shell remembers the full pathname of the command, allowing it to be found more quickly and to be issued from any directory. If no name is supplied, current tracked aliases are listed. Tracked aliases are similar to hashed commands in Bash. Korn shell only. ksh93 always does alias tracking.


-x

Export the alias; it can now be used in shell scripts and other subshells. If no name is supplied, current exported aliases are listed. Korn shell only. ksh93 accepts this option but ignores it.

Example

     alias dir='echo ${PWD##*/}' 

autoload

     autoload [functions] 

Korn shell alias for typeset -fu. Load (define) the functions only when they are first used.

bind

     bind [-m map] [options]     bind [-m map] [-q function] [-r sequence] [-u function]     bind [-m map] -f file     bind [-m map] -x sequence:command     bind [-m map] sequence:function     bind readline-command 

Bash only. Manage the readline library. Non-option arguments have the same form as in a .inputrc file.

Options


-f file

Read key bindings from file.


-l

List the names of all the readline functions.


-m map

Use map as the keymap. Available keymaps are: emacs, emacs-standard, emacs-meta, emacs-ctlx, vi, vi-move, vi-command, and vi-insert. vi is the same as vi-command, and emacs is the same emacs-standard.


-p

Print the current readline bindings such that they can be reread from a .inputrc file.


-P

Print the current readline bindings.


-q function

Query which keys invoke the readline function function.


-r sequence

Remove the binding for key sequence sequence.


-s

Print the current readline key sequence and macro bindings such that they can be reread from a .inputrc file.


-S

Print the current readline key sequence and macro bindings.


-u function

Unbind all keys that invoke the readline function function.


-v

Print the current readline variables such that they can be reread from a .inputrc file.


-V

Print the current readline variables.


-x sequence:command

Execute the shell command command whenever sequence is entered.

bg

     bg [jobIDs] 

Put current job or jobIDs in the background. See the earlier section Job Control."

break

     break [n] 

Exit from a for, while, select, or until loop (or break out of n loops).

builtin

     builtin command [ arguments ... ] 

Bash version. Run the shell built-in command command with the given arguments. This allows you to bypass any functions that redefine a built-in command's name. The command command is more portable.

Example

This function lets you do your own tasks when you change directory:

     cd (  ) {             builtin cd "$@"      Actually change directory             pwd           Report location         } 

builtin

     builtin [ -ds ] [ -f library ] [ name ... ] 

ksh93 version. This command allows you to load new built-in commands into the shell at runtime from shared library files.

If no arguments are given, builtin prints all the built-in command names. With arguments, builtin adds each name as a new built-in command (like cd or pwd). If the name contains a slash, the newly added built-in version is used only if a path search would otherwise have found a command of the same name. (This allows replacement of system commands with faster, built-in versions.) Otherwise, the built-in command is always found.

Options


-d

Delete the built-in command name.


-f

Load new built-in command from library.


-s

Only print "special" built-ins (those designated as special by POSIX).

case

 case value in  pattern1) cmds1;;  pattern2) cmds2;;  .  .  . esac 

Execute the first set of commands (cmds1) if value matches pattern1, execute the second set of commands (cmds2) if value matches pattern2, etc. Be sure the last command in each set ends with ;;. value is typically a positional parameter or other shell variable. cmds are typically Unix commands, shell programming commands, or variable assignments. Patterns can use file-generation metacharacters. Multiple patterns (separated by |) can be specified on the same line; in this case, the associated cmds are executed whenever value matches any of these patterns. See the Examples here and under eval.

The shells allow pattern to be preceded by an optional open parenthesis, as in (pattern). In Bash and ksh88, it's necessary for balancing parentheses inside a $( ) construct.

The Korn shell allows a case to end with ;& instead of ;;. In such cases, control "falls through" to the group of statements for the next pattern.

Examples

Check first command-line argument and take appropriate action:

     case $1 in     # Match the first arg             no|yes) response=1;;             -[tT])  table=TRUE;;             *)      echo "unknown option"; exit 1;;     esac 

Read user-supplied lines until user exits:

     while :        # Null command; always true         do            printf "Type . to finish =  => "            read line            case "$line" in               .) echo "Message done"                  break ;;               *) echo "$line" >> $message ;;            esac         done 

caller

     caller [expression] 

Bash only. Print the line number and source file name of the current function call or dot file. With nonzero expression, prints that element from the call stack. The most recent is zero. This command is for use by the Bash debugger.

cd

     cd [-LP] [dir]     cd [-LP] [-]     cd [-LP] [old new] 

With no arguments, change to home directory of user. Otherwise, change working directory to dir. If dir is a relative pathname but is not in the current directory, the CDPATH variable is searched. A directory of - stands for the previous directory. The last syntax is specific to the Korn shell. It modifies the current directory name by replacing string old with new and then switches to the resulting directory.

Options


-L

Use the logical path (what the user typed, including any symbolic links) for cd .. and the value of PWD. This is the default.


-P

Use the actual filesystem physical path for cd .. and the value of PWD.

Example

     $ pwd          /var/spool/cron         $ cd cron uucp     Ksh: cd prints the new directory         /var/spool/uucp

command

     command [-pvV] name [arg ...] 

Not ksh88. Without -v or -V, execute name with given arguments. This command bypasses any aliases or functions that may be defined for name. When used with a special built-in, it prevents the built-in from exiting the script if it fails.

Options


-p

Use a predefined, default search path, not the current value of PATH.


-v

Print a description of how the shell interprets name.


-V

Print a more verbose description of how the shell interprets name.

Example

Create an alias for rm that will get the system's version, and run it with the -i option:

     $ alias 'rm=command -p rm -i' 

compgen

     compgen [options] [string] 

Bash only. Generate possible completions for string according to the options. Options are those accepted by complete, except for -p and -r. For more information, see the entry for complete.

complete

     complete [options] command ... 

Bash only. Specify the way to complete arguments for each command. This is discussed in See Programmable Completion (Bash only)," earlier in the chapter.

Options


-a

Same as -A alias.


-A type

Use type to specify a list of possible completions. The type may be one of the following.


alias

Alias names.


arrayvar

Array variable names.


binding

Bindings from the readline library.


builtin

Shell built-in command names.


directory

Directory names.


disabled

Names of disabled shell built-in commands.


enabled

Names of enabled shell built-in commands.


function

Names of shell functions.


group

Group names.


helptopic

Help topics as allowed by the help built-in command.


hostname

Hostnames, as found in the file named by $HOSTFILE.


job

Job names.


keyword

Shell reserved keywords.


running

Names of running jobs.


service

Service names (from /etc/services).


setopt

Valid arguments for set -o.


shopt

Valid option names for the shopt built-in command.


signal

Signal names.


stopped

Names of stopped jobs.


user

Usernames.


variable

Shell variable names.


-b

Same as -A builtin.


-c

Same as -A command.


-C command

Run command in a subshell and use its output as the list of completions.


-d

Same as -A directory.


-e

Same as -A export.


-f

Same as -A file.


-F function

Run shell function function in the current shell. Upon its return, retrieve the list of completions from the COMPREPLY array.


-g

Same as -A group.


-G pattern

Expand pattern to generate completions.


-j

Same as -A job.


-k

Same as -A keyword.


-o option

Control the behavior of the completion specification. The value for option is one of the following.


bashdefault

Fall back to the normal Bash completions if no matches are produced.


default

Use the default readline completions if no matches are produced.


dirnames

Do directory name completion if no matches are produced.


filenames

Inform the readline library that the intended output is filenames, so that the library can do any filename-specific processing, such as adding a trailing slash for directories or removing trailing spaces.


nospace

Inform the readline library that it should not append a space to words completed at the end of a line.


plusdirs

Attempt directory completion and add any results to the list of completions already generated.


-p

With no commands, print all completion settings in a way that can be reread.


-P prefix

The prefix is added to each resulting string as a prefix after all the other options have been applied.


-r

Remove the completion settings for the given commands, or all settings if no commands.


-s

Save as -A service.


-S suffix

The suffix is added to each resulting string as a suffix after all the other options have been applied.


-u

Same as -A user.


-v

Same as -A variable.


-W wordlist

Split wordlist (a single shell word) using $IFS. The generated list contains the members of the split list that matched the word being completed. Each member is expanded using brace expansion, tilde expansion, parameter and variable expansion, command substitution, and arithmetic expansion. Shell quoting is respected.


-X pattern

Exclude filenames matching pattern from the filename completion list. With a leading !, the sense is reversed, and only filenames matching pattern are retained.

continue

     continue [n] 

Skip remaining commands in a for, while, select, or until loop, resuming with the next iteration of the loop (or skipping n loops).

declare

     declare [options] [name[=value]] 

Bash only. Declare variables and manage their attributes. In function bodies, variables are local, as if declared with the local command.

Options


-a

Each name is an array.


-f

Each name is a function.


-F

For functions, print just the functions' name and attributes, not the function definition (body).


-i

Each variable is an integer; in an assignment, the value is evaluated as an arithmetic expression.


-p

With no names, print all variables and their values. With names, print the names, attributes, and values of the given variables. This option causes all other options to be ignored.


-r

Mark names as read-only. Subsequent assignments will fail.


-t

Apply the trace attribute to each name. Traced functions inherit the DEBUG trap. This attribute has no meaning for variables.


-x

Mark names for export into the environment of child processes.

With a + instead of a -, the given attribute is disabled. With no variable names, all variables having the given attribute(s) are printed in a form that can be reread as input to the shell.

Examples

     $ declare -i val      Make val an integer         $ val=4+7         Evaluate value         $ echo $val       Show result         11          $ declare -r z=42        Make z read-only         $ z=31            Try to assign to it         bash: z: readonly variable     Assignment fails         $ echo $z          42                 $ declare -p val z       Show attributes and values         declare -i val="11"         declare -r z="42"

dirs

     dirs [-clpv] [+n] [-n] 

Bash only. Print the directory stack, which is managed with pushd and popd.

Options


+n

Print the nth entry from the left; first entry is zero.


-n

Print the nth entry from the right; first entry is zero.


-c

Remove all entries from (clear) the directory stack.


-l

Produce a longer listing, one that does not replace $HOME with ~.


-p

Print the directory stack, one entry per line.


-v

Print the directory stack, one entry per line, with each entry preceded by its index in the stack.

disown

     disown [-ahr] [job ...] 

Bash version. Remove job from the list of jobs managed by Bash.

Options


-a

Remove all jobs. With -h, mark all jobs.


-h

Instead of removing jobs from the list of known jobs, mark them to not receive SIGHUP when Bash exits.


-r

With no jobs, remove (or mark) only running jobs.

disown

     disown [job ...] 

ksh93 version. When a login shell exits, do not send a SIGHUP to the given jobs. If no jobs are listed, no background jobs will receive SIGHUP.

do

     do 

Reserved word that precedes the command sequence in a for, while, until, or select statement.

done

     done 

Reserved word that ends a for, while, until, or select statement.

echo

     echo [-eEn] [string] 

Bash version, built into the shell. Write string to standard output. (See also echo in Chapter 3.)

Options


-e

Enable interpretation of the following escape sequences, which must be quoted (or escaped with a \) to prevent interpretation by the shell:


\a

Alert (ASCII BEL).


\b

Backspace.


\c

Suppress the terminating newline (same as -n).


\e

ASCII Escape character.


\f

Formfeed.


\n

Newline.


\r

Carriage return.


\t

Tab character.


\v

Vertical-tab character.


\\

Backslash.


\0nnn

ASCII character represented by octal number nnn, where nnn is zero, one, two, or three digits and is preceded by a 0.


\nnn

ASCII character represented by octal number nnn, where nnn is one, two, or three digits.


\xHH

ASCII character represented by hexadecimal number HH, where HH is one or two hexadecimal digits.


-E

Do not interpret escape sequences, even on systems where the default behavior of the built-in echo is to interpret them.


-n

Do not print the terminating newline.

Examples

     $ echo "testing printer" | lp     $ echo "Warning: ringing bell \a" 

echo

     echo [-n] [string] 

Korn shell version. Write string to standard output; if -n is specified, the output is not terminated by a newline. If no string is supplied, echo a newline.

The Korn shell's echo, even though it is built into the shell, emulates the system's version of echo. Thus, if the version found by a path search supports -n, the built-in version does, too. Similarly, if the external version supports the escape sequences described below, the built-in version does, too; otherwise it does not.[*] (See also echo in Chapter 3.) echo understands special escape characters, which must be quoted (or escaped with a \) to prevent interpretation by the shell:

[*] The situation with echo is a mess; consider using printf instead.


\a

Alert (ASCII BEL).


\b

Backspace.


\c

Suppress the terminating newline (same as -n).


\f

Formfeed.


\n

Newline.


\r

Carriage return.


\t

Tab character.


\v

Vertical-tab character.


\\

Backslash.


\0nnn

ASCII character represented by octal number nnn, where nnn is one, two, or three digits and is preceded by a 0.

enable

     enable [-adnps] [-f file] [command ...] 

Bash only. Enable or disable shell built-in commands. Disabling a built-in lets you use an external version of a command that would otherwise use a built-in version, such as echo or test.

Options


-a

For use with -p, print information about all built-in commands, disabled and enabled.


-d

Remove (delete) a built-in previously loaded with -f.


-f file

Load a new built-in command command from the shared library file file.


-n

Disable the named built-in commands.


-p

Print a list of enabled built-in commands.


-s

Print only the POSIX special built-in commands. When combined with -f, the new built-in command becomes a POSIX special built-in.

esac

     esac 

Reserved word that ends a case statement.

eval

     eval args 

Typically, eval is used in shell scripts, and args is a line of code that contains shell variables. eval forces variable expansion to happen first and then runs the resulting command. This "double-scanning" is useful any time shell variables contain input/output redirection symbols, aliases, or other shell variables. (For example, redirection normally happens before variable expansion, so a variable containing redirection symbols must be expanded first using eval; otherwise, the redirection symbols remain uninterpreted.)

Example

This fragment of a shell script shows how eval constructs a command that is interpreted in the right order:

     for option     do         case "$option" in   Define where output goes            save) out=' > $newfile' ;;            show) out=' | more' ;;         esac      done             eval sort $file $out 

exec

     exec [command args ...]     exec [-a name] [-cl] [command args ... ] 

Execute command in place of the current process (instead of creating a new process). exec is also useful for opening, closing, or copying file descriptors. The second form is for ksh93 and Bash.

Options


-a

Use name for the value of argv[0].


-c

Clear the environment before executing the program.


-l

Place a minus sign at the front of argv[0], just as login(1) does. Bash only.

Examples

     trap 'exec 2>&-' 0        Close standard error when                              shell script exits (signal 0)       $ exec /bin/csh      Replace shell with C shell     $ exec < infile       Reassign standard input to infile 

exit

     exit [n] 

Exit a shell script with status n (e.g., exit 1). n can be 0 (success) or nonzero (failure). If n is not given, exit status is that of the most recent command. exit can be issued at the command line to close a window (log out). Exit statuses can range in value from 0 to 255.

Example

     if [ $# -eq 0 ]     then        echo "Usage: $0 [-c] [-d] file(s)" 1>&2        exit 1               # Error status     fi 

export

     export [variables]     export [name=[value] ...]     export -p     export [-fn] [name=[value] ...] 

Pass (export) the value of one or more shell variables, giving global meaning to the variables (which are local by default). For example, a variable defined in one shell script must be exported if its value is used in other programs called by the script. If no variables are given, export lists the variables exported by the current shell. The second form is the POSIX version, which is similar to the first form, except that you can set a variable name to a value before exporting it. The third form is not available in ksh88. The fourth form is specific to Bash.

Options


-f

Names refer to functions; the functions are exported in the environment. Bash only.


-n

Remove the named variables or functions from the environment. Bash only.


-p

Print export before printing the names and values of exported variables. This allows saving a list of exported variables for rereading later.

Example

In the original Bourne shell, you would type:

     TERM=vt100     export TERM 

In Bash and the Korn shell, you could type this instead:

     export TERM=vt100 

false

     false 

ksh88 alias for let 0. Built-in command in Bash and ksh93 that exits with a false return value.

fc

     fc [options] [first [last]]     fc -e - [old=new] [command]     fc -s [old=new] [command] 

ksh88 and Bash. Display or edit commands in the history list. (Use only one of -e, -l or -s.) first and last are numbers or strings specifying the range of commands to display or edit. If last is omitted, fc applies to a single command (specified by first). If both first and last are omitted, fc edits the previous command or lists the last 16. The second form of fc takes a history command, replaces old with new, and executes the modified command. If no strings are specified, command is just reexecuted. If no command is given either, the previous command is reexecuted. command is a number or string like first. See the examples in the earlier section Command History." The third form, available in Bash and ksh93, is equivalent to the second form.

Options


-e [editor]

Invoke editor to edit the specified history commands. The default editor is set by the shell variable FCEDIT. If that variable is not set, the default is /bin/ed. (Bash defaults to vi; Version 3.1 and newer will default to /bin/ed when in POSIX mode.) Bash tries FCEDIT, then EDITOR, and then /bin/ed.


-e -

Execute (or redo) a history command; refer to second syntax line above.


-l

List the specified command or range of commands, or list the last 16.


-n

Suppress command numbering from the -l listing.


-r

Reverse the order of the -l listing.


-s

Equivalent to -e -. Not in ksh88.

fc

     fc 

ksh93 alias for hist.

fg

     fg [jobIDs] 

Bring current job or jobIDs to the foreground. See the earlier section Job Control."

fi

     fi 

Reserved word that ends an if statement. (Don't forget to use it!)

for

     for x [in list]     do      commands     done 

For variable x (in optional list of values) do commands. If in list is omitted, "$@" (the positional parameters) is assumed.

Examples

Paginate files specified on the command line; save each result:

     for file; do          pr $file > $file.tmp     done 

Search chapters for a list of words (like fgrep -f):

     for item in `cat program_list`     do          echo "Checking chapters for"          echo "references to program $item..."          grep -c "$item.[co]" chap*     done 

Extract a one-word title from each file and use as new filename:

     for file     do          name=`sed -n 's/NAME: //p' $file`          mv $file $name     done 

for

     for ((init; cond; incr))     do      commands     done 

Bash and ksh93. Arithmetic for loop, similar to C's. Evaluate init. While cond is true, execute the body of the loop. Evaluate incr before retesting cond. Any one of the expressions may be omitted; a missing cond is treated as being true.

Examples

Search for a phrase in each odd chapter:

     for ((x=1; x <= 20; x += 2))     do             grep $1 chap$x     done 

function

     function name { commands; }     function name (  ) { commands; } 

Define name as a shell function. See the description of semantic issues in the earlier section Functions." The first form is for the Korn shell, although it may also be used with Bash. The second form is specific to Bash. Bash does not give different semantics to functions declared differently; all Bash functions behave the same way.

Example

Define a function to count files:

     $ function fcount {     >    ls | wc -l     > } 

functions

     functions 

Korn shell alias for typeset -f. (Note the "s" in the name; function is a Korn shell keyword.) See typeset later in this listing.

getconf

     getconf [name [path]] 

ksh93 only. Retrieve the values for parameters that can vary across systems. name is the parameter to retrieve; path is a filename to test for parameters that can vary on different filesystem types.

The parameters are defined by the POSIX 1003.1 standard. See the entry for getconf in Chapter 3.

Example

Print the maximum value that can be held in a C int:

     $ getconf INT_MAX     2147483647 

getopts

     getopts [-a name] string name [args] 

Process command-line arguments (or args, if specified) and check for legal options. getopts is used in shell-script loops and is intended to ensure standard syntax for command-line options. Standard syntax dictates that command-line options begin with a -. Options can be stacked: i.e., consecutive letters can follow a single -. End processing of options by specifying -- on the command line. string contains the option letters to be recognized by getopts when running the shell script. Valid options are processed in turn and stored in the shell variable name. If an option is followed by a colon, the option must be followed by one or more arguments. (Multiple arguments must be given to the command as one shell word. This is done by quoting the arguments or separating them with commas. The application must be written to expect multiple arguments in this format.) getopts uses the shell variables OPTARG and OPTIND. The Bash version also uses OPTERR.

Option


-a

Use name in error messages about invalid options. ksh93 only.

hash

     hash [-dlrt] [-p file] [commands] 

Bash version. As the shell finds commands along the search path ($PATH), it remembers the found location in an internal hash table. The next time you enter a command, the shell uses the value stored in its hash table.

With no arguments, hash lists the current hashed commands. The display shows hits (the number of times the command is called by the shell) and the command name.

With commands, the shell adds those commands to the hash table.

Options


-d

Remove (delete) just the specified commands from the hash table.


-l

Produce output in a format that can be reread to rebuild the hash table.


-p file

Associate file with command in the hash table.


-r

Remove all commands from the hash table.


-t

With one name, print the full pathname of the command. With more than one name, print the name and the full path, in two columns.

Besides the -r option, the hash table is also cleared when PATH is assigned. Use PATH=$PATH to clear the hash table without affecting your search path. This is most useful if you have installed a new version of a command in a directory that is earlier in $PATH than the current version of the command.

hash

     hash 

Korn shell alias for alias -t (alias -t -- in ksh93). Approximates the Bourne shell's hash.

help

     help [-s] [pattern] 

Bash only. Print usage information on standard output for each command that matches pattern. The information includes descriptions of each command's options. With the -s option, print only brief usage information.

Examples

     $ help -s cd          Short help     cd: cd [-L|-P] [dir]           $ help true           Full help     true: true         Return a successful result. 

hist

     hist [options] [first [last]]     hist -s [old=new] [command] 

ksh93 only. Display or edit commands in the history list. (Use only one of -l or -s.) first and last are numbers or strings specifying the range of commands to display or edit. If last is omitted, hist applies to a single command (specified by first). If both first and last are omitted, hist edits the previous command or lists the last 16. The second form of hist takes a history command, replaces old with new, and executes the modified command. If no strings are specified, command is just reexecuted. If no command is given either, the previous command is reexecuted. command is a number or string like first. See the examples in the earlier section Command History."

Options


-e [editor]

Invoke editor to edit the specified history commands. The default editor is set by the shell variable HISTEDIT. If that variable is not set, FCEDIT is used. If neither is set, the default is /bin/ed.


-l

List the specified command or range of commands, or list the last 16.


-n

Suppress command numbering from the -l listing.


-N n

Start with the command n commands before the current one.


-r

Reverse the order of the -l listing.


-s

Execute (or redo) a history command; refer to second syntax line above.

history

     history [count]     history [options] 

Bash version. Print commands in the history list or manage the history file. With no options or arguments, display the history list with command numbers. With a count argument, print only that many of the most recent commands.

Options


-a

Append new history lines (those executed since the beginning of the session) to the history file.


-c

Clear the history list (remove all entries).


-d position

Delete the history item at position position.


-n

Read unread history lines from the history file into the history list.


-p argument ...

Perform csh-style history expansion on each argument, printing the results to standard output. The results are not saved in the history list.


-r

Read the history file and replace the history list with its contents.


-s argument ...

Store the arguments in the history list, as a single entry.


-w

Write the current history list to the history file, overwriting it entirely.

history

     history 

ksh88 alias for fc -l. ksh93 alias for hist -l. Show the last 16 commands.

if

     if condition1then commands1     [ elif condition2 then commands2 ]      .      .      .     [ else commands3 ]     fi 

If condition1 is met, do commands1; otherwise, if condition2 is met, do commands2 ; if neither is met, do commands3. Conditions are often specified with the test and [[ ]] commands. See test and [[ ]] for a full list of conditions, and see additional Examples under : and exit.

Examples

Insert a 0 before numbers less than 10:

     if [ $counter -lt 10 ]     then number=0$counter     else number=$counter     fi 

Make a directory if it doesn't exist:

     if [ ! -d $dir ]; then        mkdir $dir        chmod 775 $dir     fi 

integer

     integer 

Korn shell alias for typeset -i. Specify integer variables.

jobs

     jobs [options] [jobIDs] 

List all running or stopped jobs, or list those specified by jobIDs. For example, you can check whether a long compilation or text format is still running. Also useful before logging out. See the earlier section Job Control."

Options


-l

List job IDs and process group IDs.


-n

List only jobs whose status changed since last notification.


-p

List process group IDs only.


-r

List running jobs only. Bash only.


-x cmd

Replace each job ID found in cmd with the associated process ID and then execute cmd. Bash only.

kill

     kill [options] IDs 

Terminate each specified process ID or job ID. You must own the process or be a privileged user. This built-in command is similar to /usr/bin/kill, described in Chapter 3. See the earlier section Job Control."

Options


-l

List the signal names. (Used by itself.)


-n num

Send the given signal number. Not ksh88.


-s name

Send the given signal name. Not ksh88.


-signal

The signal number (from /usr/include/sys/signal.h) or name (from kill -l). With a signal number of 9, the kill is absolute.

Signals

Signals are defined in /usr/include/sys/signal.h and are listed here without the SIG prefix. The correspondence between signal name and signal number shown in the following table is correct for Linux; many are different on other Unix-style operating systems.

Name

Number

Description

HUP

1

Hangup

INT

2

Interrupt (usually invoked by user through Ctrl-C)

QUIT

3

Quit

ILL

4

Illegal instruction

TRAP

5

Trace trap

ABRT

6

Abort

IOT

6

IOT trap

BUS

7

Bus error (a type of illegal address access)

FPE

8

Floating-point exception (example: division by 0)

KILL

9

Kill, unblockable (often used with INT fails to terminate process)

USR1

10

User-defined signal 1

SEGV

11

Segmentation violation (a type of illegal address access)

USR2

12

User-defined signal 2

PIPE

13

Broken pipe (generated when process on one side of pipe is aborted)

ALRM

14

Alarm clock (used for delivering timed alerts from a program)

TERM

15

Termination

STKFLT

16

Stack fault (a type of illegal address access)

CLD or CHLD

17

Child status has changed

CONT

18

Continue (issued after STOP or TSTP)

STOP

19

Stop, unblockable

TSTP

20

Stop (issued at terminal, usually through Ctrl-Z)

TTIN

21

Attempt to read from terminal while in background

TTOU

22

Unsuccessful attempt to write to terminal while in background

URG

23

Urgent condition on socket

XCPU

24

CPU usage limit exceeded

XFSZ

25

File size limit exceeded

VTALRM

26

Virtual alarm clock

PROF

27

Profiling alarm clock

WINCH

28

Window size change

IO or POLL

29

Ready for I/O (used in applications for interrupts)

PWR

30

Power failure restart

SYS

31

Bad system call


let

     let expressions or     ((expressions)) 

Perform arithmetic as specified by one or more expressions. expressions consist of numbers, operators, and shell variables (which don't need a preceding $). Expressions must be quoted if they contain spaces or other special characters. The (( )) form does the quoting for you. For more information and examples, see Arithmetic Expressions," earlier in this chapter. See also expr in Chapter 3.

Examples

Each of these examples adds 1 to variable i:

     i=`expr $i + 1`         All Bourne shells     let i=i+1        Bash, ksh     let "i = i + 1"     (( i = i + 1 ))     (( i += 1 ))     (( i++ ))        Bash, ksh93 

local

     local [options] [name[=value]] 

Bash only. Declares local variables for use inside functions. The options are the same as those accepted by declare; see declare for the full list. It is an error to use local outside a function body.

login

     login [user] 

Korn shell only. The shell does an execve(2) of the standard login program, allowing you to replace one login session with another, without having to logout first.

logout

     logout 

Bash only. Exit a login shell. The command fails if the current shell is not a login shell.

name ( )

     name (  ) { commands; } 

Define name as a function. POSIX syntax. The function definition can be written on one line or across many. Bash and the Korn shell provide the function keyword, alternate forms that work similarly. See the Functions section, earlier in the chapter.

Example

     $ count (  ) {     > ls | wc -l     > } 

When issued at the command line, count now displays the number of files in the current directory.

nameref

     nameref newvar=oldvar ... 

ksh93 alias for typeset -n. See the discussion of indirect variables in the Variables section, earlier in this chapter.

nohup

     nohup command [arguments] & 

Don't terminate a command after logout. nohup is a Korn shell alias:

     nohup='nohup ' 

The embedded space at the end lets nohup interpret the following command as an alias, if needed.

popd

     popd [-n] [+count] [-count] 

Bash only. Pop the top directory off the directory stack (as shown by the dirs command), and change to the new top directory, or manage the directory stack.

Options


-n

Don't change to the new top directory; just manipulate the stack.


+count

Remove the item count entries from the left, as shown by dirs. Counting starts at zero. No directory change occurs.


-count

Remove the item count entries from the right, as shown by dirs. Counting starts at zero. No directory change occurs.

print

     print [options] [string ...] 

Korn shell only. Display string (on standard output by default). print includes the functions of echo and can be used in its place on most Unix systems.

Options


-

Ignore all subsequent options.


--

Same as -.


-e

Interpret escape sequences in argument strings. (This is the default, anyway.) Use it to undo an earlier -r in the same command line. ksh93 only.


-f format

Print like printf, using format as the format string. Ignores the -n, -r, and -R options. ksh93 only.


-n

Don't end output with a newline.


-p

Send string to the process created by |&, instead of to standard output.


-r

Ignore the escape sequences often used with echo.


-R

Same as -r and ignore subsequent options (except -n).


-s

Send string to the history file.


-u[n]

Send string to file descriptor n (default is 1).

printf

     printf format [val ...] 

Not ksh88. Formatted printing, like the ANSI C printf function.

Additional Format Letters

Both Bash and ksh93 accept additional format letters. Bash provides only %b and %q, while ksh93 provides all those in the following list:


%b

Expand escape sequences in strings (e.g., \t to tab, and so on).


%B

The corresponding argument is a variable name (typically created via typeset -b); its value is retrieved and printed.


%d

An additional period and the output base can follow the precision (e.g., %5.3.6d to produce output in base 6).


%H

Output strings in HTML/XML format. (Spaces become &nbsp; and < and > become &lt; and &gt;.)


%n

Place the number of characters printed so far into the named variable.


%P

Translate egrep extended regular expression into ksh pattern.


%q

Print a quoted string that can be reread later on.


%R

Reverse of %P: translate ksh pattern into egrep extended regular expression.


%(format)T

Print a string representing a date and time according to the strftime(3) format format. The parentheses are entered literally. See the Examples.


%Z

Print an ASCII NUL (8 zero bits).

Examples

     $ date               Reformat date/time     Tue Sep  7 15:39:42 EDT 2004     $ printf "%(It is now %m/%d/%Y %H:%M:%S)T\n" "$(date)"      It is now 09/07/2004 15:40:10           $ printf "%H\n" "Here is a <string>"      Convert to HTML     Here&nbsp;is&nbsp;a&nbsp;&lt;string&gt; 

pushd

     pushd [-n] [directory]     pushd [-n] [+count] [-count] 

Bash only. Add directory to the directory stack, or rotate the directory stack. With no arguments, swap the top two entries on the stack, and change to the new top entry.

Options


-n

Don't change to the new top directory, just manipulate the stack.


+count

Rotate the stack so that the count'th item from the left, as shown by dirs, is the new top of the stack. Counting starts at zero. The new top becomes the current directory.


-count

Rotate the stack so that the count'th item from the left, as shown by dirs, is the new top of the stack. Counting starts at zero. The new top becomes the current directory.

pwd

     pwd [-LP] 

Print your present working directory on standard output.

Options

Options give control over the use of logical versus physical treatment of the printed path. See also the entry for cd, earlier in this section.


-L

Use logical path (what the user typed, including any symbolic links) and the value of PWD for the current directory. This is the default.


-P

Use the actual filesystem physical path for the current directory.

r

     r 

ksh88 alias for fc -e -. ksh93 alias for hist -s. Reexecute previous command.

read

     read [options] [variable1[?string]] [variable2 ...] 

Read one line of standard input and assign each word to the corresponding variable, with all leftover words assigned to the last variable. If only one variable is specified, the entire line is assigned to that variable. See the Examples here and under case. The return status is 0 unless EOF is reached. Both Bash and the Korn shell support options, as shown below. If no variables are given, input is stored in the REPLY variable.

Additionally, the Korn shell version supports the ? syntax for prompting. If the first variable is followed by ?string, string is displayed as a user prompt.

Options


-a array

Read into indexed array array. Bash only.


-A array

Read into indexed array array. ksh93 only.


-d delim

Read up to first occurrence of delim, instead of newline. Not ksh88.


-e

Use the readline library if reading from a terminal. Bash only.


-n count

Read at most count bytes. Not ksh88.


-p prompt

Bash: print prompt before reading input.


-p

Korn shell: read from the output of a |& coprocess.


-r

Raw mode; ignore \ as a line-continuation character.


-s

Bash: read silently; characters are not echoed.


-s

Korn shell: save input as a command in the history file.


-t timeout

When reading from a terminal or pipe, if no data is entered after timeout seconds, return 1. This prevents an application from hanging forever, waiting for user input. Not ksh88.


-u[n]

Read input from file descriptor n (default is 0).

Examples

Read three variables:

     $ read first last address     Sarah Caldwell 123 Main Street           $ echo "$last, $first\n$address"     Caldwell, Sarah     123 Main Street 

Prompt yourself to enter two temperatures, Korn shell version:

     $ read n1?"High low: " n2     High low: 65 33 

readonly

     readonly [-afp] [variable[=value] ...] 

Prevent the specified shell variables from being assigned new values. An initial value may be supplied using the assignment syntax, but that value may not be changed subsequently.

Options

ksh88 does not accept options for this command.


-a

Each variable must refer to an array. Bash only.


-f

Each variable must refer to an function. Bash only.


-p

Print readonly before printing the names and values of read-only variables. This allows saving a list of read-only variables for rereading later.

redirect

     redirect i/o-redirection ... 

ksh93 alias for command exec.

Example

Change the shell's standard error to the console:

     $ redirect 2>/dev/console 

return

     return [n] 

Use inside a function definition. Exit the function with status n or with the exit status of the previously executed command.

select

     select x [in list]     do      commandsdone 

Display a list of menu items on standard error, numbered in the order they are specified in list. If no in list is given, items are taken from the command line (via "$@"). Following the menu is a prompt string (set by PS3). At the PS3 prompt, users select a menu item by typing its line number, or they redisplay the menu by pressing the Enter key. User input is stored in the shell variable REPLY. If a valid item number is typed, commands are executed. Typing EOF terminates the loop.

Example

     PS3="Select the item number: "     select event in Format Page View Exit     do        case "$event" in          Format) nroff $file | lp;;          Page)   pr $file | lp;;          View)   more $file;;          Exit)   exit 0;;          *   )   echo "Invalid selection";;        esac     done 

The output of this script looks like this:

     1. Format     2. Page     3. View     4. Exit     Select the item number: 

set

     set [options arg1 arg2 ...] 

With no arguments, set prints the values of all variables known to the current shell. Options can be enabled (-option) or disabled (+option). Options can also be set when the shell is invoked. (See the earlier section Invoking the Shell.") Arguments are assigned in order to $1, $2, etc.

Options

There is a large set of overlapping options among ksh88, ksh93 and Bash. To minimize confusion, the following list includes every option. The table provided after the list summarizes which options are available in which shells.


-a

From now on, automatically mark variables for export after defining or changing them.


+A name

Assign remaining arguments as elements of array name. Korn shell only.


-A name

Same as +A, but unset name before making assignments. Korn shell only.


-b

Print job completion messages as soon as jobs terminate; don't wait until the next prompt. Not ksh88.


-B

Enable brace expansion. On by default. Bash only.


-C

Prevent overwriting via > redirection; use >| to overwrite files. Not ksh88.


-e

Exit if a command yields a nonzero exit status. The ERR trap executes before the shell exits.


-E

Cause shell functions, command substitutions, and subshells to inherit the ERR trap. Bash only.


-f

Ignore filename metacharacters (e.g., * ? [ ]).


-G

Cause ** to also match subdirectories during filename expansion. ksh93 only.


-h

Locate commands as they are defined. The Korn shell creates tracked aliases, whereas Bash hashes command names. On by default. See hash.


-H

Enable csh-style history substitution. On by default. Bash only.


-k

Assignment of environment variables (var=value) takes effect regardless of where they appear on the command line. Normally, assignments must precede the command name.


-m

Enable job control; background jobs execute in a separate process group. -m is usually set automatically.


-n

Read commands but don't execute; useful for checking syntax. Both shells ignore this option if is interactive.


+o [mode]

With mode, disable the given shell option. Plain set +o prints the settings of all the current options. For Bash and ksh93, this is in a form that can be reread by the shell later.


-o [mode]

List shell modes, or turn on mode mode. Many modes can be set by other options. Modes are:


allexport

Same as -a.


bgnice

Run background jobs at lower priority. Korn shell only.


braceexpand

Same as -B. Bash only.


emacs

Set command-line editor to emacs.


errexit

Same as -e.


errtrace

Same as -E. Bash only.


functrace

Same as -T. Bash only.


globstar

Same as -G. ksh93 only.


gmacs

Set command-line editor to gmacs (like GNU Emacs). Korn shell only.


hashall

Same as -h. Bash only.


histexpand

Same as -H. Bash only.


history

Enable command history. On by default. Bash only.


ignoreeof

Don't process EOF signals. To exit the shell, type exit.


keyword

Same as -k.


markdirs

Append / to directory names. Korn shell only.


monitor

Same as -m.


noclobber

Same as -C.


noexec

Same as -n.


noglob

Same as -f.


nolog

Omit function definitions from history file. Accepted but ignored by Bash.


notify

Same as -b.


nounset

Same as -u.


onecmd

Same as -t. Bash only.


physical

Same as -P. Bash only.


pipefail

Change pipeline exit status to be that of the rightmost command that failed, or zero if all exited successfully. Not ksh88.


posix

Change to POSIX mode. Bash only.


privileged

Same as -p.


trackall

Same as -h. Korn shell only.


verbose

Same as -v.


vi

Set command-line editor to vi.


viraw

Same as vi, but process each character when it's typed. Korn shell only.


xtrace

Same as -x.


+p

Reset effective UID to real UID.


-p

Start up as a privileged user. Bash: Don't read $ENV or $BASH_ENV, don't import functions from the environment, and ignore the value of $SHELLOPTS. Korn shell: Don't process $HOME/.profile, read /etc/suid_profile instead of $ENV.


-P

Always use physical paths for cd and pwd. Bash only.


-s

Sort the positional parameters. Korn shell only.


-t

Exit after one command is executed.


-T

Cause shell functions, command substitutions, and subshells to inherit the DEBUG trap. Bash only.


-u

In substitutions, treat unset variables as errors.


-v

Show each shell command line when read.


-x

Show commands and arguments when executed, preceded by the value of PS4. This provides step-by-step tracing of shell scripts.


-

Turn off -v and -x, and turn off option processing. Included for compatibility with older versions of the Bourne shell.


--

Used as the last option; -- turns off option processing so that arguments beginning with - are not misinterpreted as options. (For example, you can set $1 to -1.) If no arguments are given after --, unset the positional parameters.

Option Availability Summary

Option

Same as

ksh88

ksh93

Bash

-a

-o allexport

·

·

·

-A

 

·

·

 

-b

-o notify

 

·

·

-B

-o braceexpand

  

·

-C

-o noclobber

 

·

·

-e

-o errexit

·

·

·

-E

-o errtrace

  

·

-f

-o noglob

·

·

·

-G

-o globstar

 

·

 

-h

-o hashall

  

·

-h

-o trackall

·

·

 

-H

-o histexpand

  

·

-k

-o keyword

·

·

·

-m

-o monitor

·

·

·

-n

-o noexec

·

·

·

-o allexport

-a

·

·

·

-o bgnice

 

·

·

 

-o braceexpand

-B

  

·

-o emacs

 

·

·

·

-o errexit

-e

·

·

·

-o errtrace

-E

  

·

-o functrace

-T

  

·

-o globstar

-G

 

·

 

-o gmacs

 

·

·

 

-o hashall

-h

  

·

-o history

   

·

-o histexpand

-H

  

·

-o ignoreeof

 

·

·

·

-o keyword

-k

·

·

·

-o markdirs

 

·

·

 

-o monitor

-m

·

·

·

-o noclobber

-C

·

·

·

-o noexec

-n

·

·

·

-o noglob

-f

·

·

·

-o nolog

 

·

·

 

-o notify

-b

 

·

·

-o nounset

-u

  

·

-o onecmd

-t

  

·

-o physical

-P

  

·

-o pipefail

  

·

·

-o posix

   

·

-o privileged

-p

·

·

·

-o trackall

-h

·

·

 

-o verbose

-v

·

·

·

-o vi

 

·

·

·

-o viraw

 

·

·

 

-o xtrace

-x

·

·

·

-p

-o privileged

·

·

·

-P

-o physical

  

·

-s

 

·

·

 

-t

-o onecmd

·

·

·

-T

-o functrace

  

·

-u

-o nonunset

·

·

·

-v

-o verbose

·

·

·

-x

-o xtrace

·

·

·


Examples

     set -- "$num" -20 -30   Set $1 to $num, $2 to -20, $3 to -30     set -vx                 Read each command line; show it;                             execute it; show it again (with arguments)     set +x                  Stop command tracing     set -o noclobber        Prevent file overwriting     set +o noclobber        Allow file overwriting again 

shopt

     shopt [-opqsu] [option] 

Bash only. Sets or unsets shell options. With no options or just -p, prints the names and settings of the options.

Options


-o

Each option must be one of the shell option names for set -o, instead of the options listed in the next section.


-p

Print the option settings as shopt commands that can be reread later.


-q

Quiet mode. The exit status is zero if the given option is set, nonzero otherwise. With multiple options, all of them must be set for a zero exit status.


-s

Set the given options. With no options, prints only those that are set.


-u

Unset the given options. With no options, prints only those that are unset.

Settable Shell Options

The following descriptions describe the behavior when set. Options marked with a dagger (|) are enabled by default.


cdable_vars

Treat a nondirectory argument to cd as a variable whose value is the directory to go to.


cdspell

Attempt spelling correction on each directory component of an argument to cd. Allowed in interactive shells only.


checkhash

Check that commands found in the hash table still exist before attempting to use them. If not, perform a normal PATH search.


checkwinsize

Check the window size after each command and update LINES and COLUMNS if the size has changed.


cmdhist |

Save all lines of a multiline command in one history entry. This permits easy re-editing of multiline commands.


dotglob

Include filenames starting with a period in the results of filename expansion.


execfail

Do not exit a noninteractive shell if the command given to exec cannot be executed. Interactive shells do not exit in such a case, no matter the setting of this option.


expand_aliases |

Expand aliases created with alias. Disabled in noninteractive shells.


extdebug

Enable behavior needed for debuggers:

  • declare -F displays the source file name and line number for each function name argument.

  • When a command run by the DEBUG trap fails, the next command is skipped.

  • When a command run by the DEBUG trap inside a shell function or script sourced with . (dot) or source returns with an exit status of 2, the shell simulates a call to return.

  • BASH_ARGC and BASH_ARGV are set as described earlier.

  • Function tracing is enabled. Command substitutions, shell functions, and subshells invoked via (...) inherit the DEBUG and RETURN traps.

  • Error tracing is enabled. Command substitutions, shell functions, and subshells invoked via (...) inherit the ERROR trap.


extglob

Enable extended pattern-matching facilities such as +(...). (These were not in the Bourne shell and are not in POSIX; thus Bash requires you to enable them if you want them.)


extquote |

Allow $'...' and $"..." within ${variable} expansions inside double quotes.


failglob

Cause patterns that do not match filenames to produce an error.


force_fignore |

When doing completion, ignore words matching the list of suffixes in FIGNORE, even if such words are the only possible completions.


gnu_errfmt

Print error messages in the standard GNU format.


histappend

Append the history list to the file named by HISTFILE upon exit, instead of overwriting the file.


histreedit

Allow a user to re-edit a failed csh-style history substitution with the readline library.


histverify

Place the results of csh-style history substitution into the readline library's editing buffer, in case the user wishes to modify it further, instead of executing it directly.


hostcomplete |

If using readline, attempt hostname completion when a word containing an @ is being completed.


huponexit

Send a SIGHUP to all running jobs upon exiting an interactive shell.


interactive_comments |

Allow words beginning with # to start a comment in an interactive shell.


lithist

If cmdhist is also set, save mutliline commands to the history file with newlines instead of semicolons.


login_shell

Set by the shell when it is a login shell. This is a read-only option.


mailwarn

Print the message "The mail in mailfile has been read" when a file being checked for mail has been accessed since the last time Bash checked it.


no_empty_cmd_completion

If using readline, do not search $PATH when a completion is attempted on an empty line.


nocaseglob

Ignore letter case when doing filename matching.


nullglob

Expand patterns that do not match any files to the null string, instead of using the literal pattern as an argument.


progcomp |

Enable programmable completion.


promptvars |

Perform variable, command, and arithmetic substitution on the values of PS1, PS2 and PS4.


restricted_shell

Set by the shell when it is a restricted shell. This is a read-only option.


shift_verbose

Causes shift to print an error message when the shift count is greater than the number of positional parameters.


sourcepath |

Causes the . (dot) and source commands to search $PATH in order to find the file to read and execute.


xpg_echo

Causes echo to expand escape sequences, even without the -e or -E options.

shift

     shift [n] 

Shift positional arguments (e.g., $2 becomes $1). If n is given, shift to the left n places. Used in while loops to iterate through command-line arguments. In the Korn shell, n can be an integer expression.

Examples

     shift $1+$6          Korn shell: use expression result as shift count     shift $(($1 + $6))   Same, portable to any POSIX shell 

sleep

     sleep [n] 

ksh93 only. Sleep for n seconds. n can have a fractional part.

source

     source file [arguments] 

Bash only. Identical to the . (dot) command; see that entry.

stop

     stop [jobIDs] 

ksh88 alias for kill -STOP. ksh93 alias for kill -s STOP. Suspend the background job specified by jobIDs; this is the complement of Ctrl-Z or suspend. See the earlier section Job Control."

suspend

     suspend [-f] 

Suspend the current shell. Often used to stop an su command. In ksh88, suspend is an alias for kill -STOP $$. In ksh93, it is an alias for kill -s STOP $$. In Bash, it is a built-in command.

Options


-f

Force the suspension, even if the shell is a login shell. Bash only.

test

     test condition or     [ condition ]      or     [[ condition ]] 

Evaluate a condition and, if its value is true, return a zero exit status; otherwise, return a nonzero exit status. An alternate form of the command uses [] rather than the word test. An additional alternate form uses [[]], in which case word splitting and pathname expansion are not done. (See the [[ ]] entry.) condition is constructed using the following expressions. Conditions are true if the description holds true. Features that are specific to Bash are marked with a (B). Features that are specific to the Korn shell are marked with a (K). Features that are specific to ksh93 are marked with a (K93).

File Conditions


-a file

file exists.


-b file

file exists and is a block special file.


-c file

file exists and is a character special file.


-C file

file exists and is a contiguous file. This facility is not available on most Unix systems. (K)


-d file

file exists and is a directory.


-f file

file exists and is a regular file.


-g file

file exists, and its set-group-id bit is set.


-G file

file exists, and its group is the effective group ID.


-h file

file exists and is a symbolic link.


-k file

file exists, and its sticky bit is set.


-L file

file exists and is a symbolic link.


-N file

file exists and was modified after it was last read. (B)


-O file

file exists, and its owner is the effective user ID.


-p file

file exists and is a named pipe (fifo).


-r file

file exists and is readable.


-s file

file exists and has a size greater than zero.


-S file

file exists and is a socket.


-t [n]

The open file descriptor n is associated with a terminal device; default n is 1.


-u file

file exists, and its set-user-id bit is set.


-w file

file exists and is writable.


-x file

file exists and is executable.


f1 -ef f2

Files f1 and f2 are linked (refer to same file).


f1 -nt f2

File f1 is newer than f2.


f1 -ot f2

File f1 is older than f2.

String conditions


string

string is not null.


-n s1

String s1 has nonzero length.


-z s1

String s1 has zero length.


s1 = s2

Strings s1 and s2 are identical. s2 can be a wildcard pattern. Quote s2 to treat it literally. (See the Filename Metacharacters section, earlier in this chapter.) (K)


s1 = = s2

Strings s1 and s2 are identical. s2 can be a wildcard pattern. Quote s2 to treat it literally. Preferred over =. (B, K93)


s1 != s2

Strings s1 and s2 are not identical. s2 can be a wildcard pattern. Quote s2 to treat it literally.


s1 =~ s2

String s1 matches extended regular expression s2. Quote s2 to keep the shell from expanding embedded shell metacharacters. Strings matched by parenthesized subexpressions are placed into elements of the BASH_REMATCH array. See the description of BASH_REMATCH earlier in this chapter. (B)


s1 < s2

ASCII value of s1 precedes that of s2. (Valid only within [[ ]] construct.)


s1 > s2

ASCII value of s1 follows that of s2. (Valid only within [[ ]] construct.)

Internal shell conditions


-o opt

Option opt for set -o is on.

Integer comparisons


n1 -eq n2

n1 equals n2.


n1 -ge n2

n1 is greater than or equal to n2.


n1 -gt n2

n1 is greater than n2.


n1 -le n2

n1 is less than or equal to n2.


n1 -lt n2

n1 is less than n2.


n1 -ne n2

n1 does not equal n2.

Combined forms


(condition)

True if condition is true (used for grouping). For test and [ ], the ( )s should be quoted by a \. The form using [[ ]] doesn't require quoting the parentheses.


! condition

True if condition is false.


condition1 -a condition2

True if both conditions are true.


condition1 && condition2

True if both conditions are true. (Valid only within [[ ]] construct.)


condition1 -o condition2

True if either condition is true.


condition1 || condition2

True if either condition is true. (Valid only within [[ ]] construct.)

Examples

The following examples show the first line of various statements that might use a test condition:

     while test $# -gt 0             While there are arguments...     while [ -n "$1" ]         While there are nonempty arguments...     if [ $count -lt 10 ]     If $count is less than 10...     if [ -d RCS ]                   If the RCS directory exists...     if [ "$answer" != "y" ]         If the answer is not y...     if [ ! -r "$1" -o ! -f "$1" ]   If the first argument is not a                                     readable file or a regular file... 

time

     time commandtime [command] 

Execute command and print the total elapsed time, user time, and system time (in seconds). Same as the Unix command time (see Chapter 3), except that the built-in version can also time other built-in commands as well as all commands in a pipeline.

The second form applies to ksh93; with no command, the total user and system times for the shell and all children are printed.

times

     times 

Print accumulated process times for user and system.

times

     times 

ksh93 alias for { {time;} 2>&1;}. See also time.

trap

     trap [ [commands] signals]     trap -p     trap -l 

Execute commands if any signals are received. The second form is specific to Bash and ksh93; it prints the current trap settings in a form suitable for rereading later. The third form is specific to Bash; it lists all signals and their numbers, like kill -l.

Common signals include EXIT (0), HUP (1), INT (2), and TERM (15). Multiple commands must be quoted as a group and separated by semicolons internally. If commands is the null string (i.e., trap "" signals), signals are ignored by the shell. If commands are omitted entirely, reset processing of specified signals to the default action. Bash and ksh93: if commands is "-", reset signals to their initial defaults.

If both commands and signals are omitted, list current trap assignments. See the Examples here and in exec.

Signals

A list of signal names, numbers, and meanings were given earlier in the kill entry; see the listing there. The shells allow you to use either the signal number or the signal name (without the SIG prefix). In addition, the shells support "pseudo-signals," signal names or numbers that aren't real operating system signals but which direct the shell to perform a specific action. These signals are:


DEBUG

Execution of any command.


ERR

Nonzero exit status.


EXIT

Exit from shell (usually when shell script finishes).


0

Same as EXIT, for historical compatibility with the Bourne shell.


KEYBD

A key has been read in emacs, gmacs, or vi editing mode. ksh93 only.


RETURN

A return is executed, or a script run with . (dot) or source finishes. Bash only.

Examples

     trap "" INT       Ignore interrupts (signal 2)     trap INT          Obey interrupts again 

Remove a $tmp file when the shell program exits, or if the user logs out, presses Ctrl-C, or does a kill:

     trap "rm -f $tmp; exit" EXIT HUP INT TERM       POSIX style     trap "rm -f $tmp; exit" 0 1 2 15    Pre-POSIX Bourne shell style 

Print a "clean up" message when the shell program receives signals SIGHUP, SIGINT, or SIGTERM:

     trap 'echo Interrupt!  Cleaning up...' HUP INT TERM 

true

     true 

ksh88 alias for :. Bash and ksh93 built-in command that exits with a true return value.

type

     type [-afpPt] commands 

Bash version. Show whether each command name is a Unix command, a built-in command, an alias, a shell keyword, or a defined shell function.

Options


-a

Print all locations in $PATH that include command, including aliases and functions. Use -p together with -a to suppress aliases and functions.


-f

Suppress function lookup, as with command.


-p

If type -t would print file for a given command, this option prints the full pathname for the executable files. Otherwise, it prints nothing.


-P

Like -p, but force a PATH search, even if type -t would not print file.


-t

Print a word describing each command. The word is one of alias, builtin, file, function, or keyword, depending upon the type of each command.

Example

     $ type mv read if     mv is /bin/mv     read is a shell builtin     if is a shell keyword 

type

     type commands 

Korn shell alias for whence -v.

typeset

     typeset [options] [variable[=value ...]]     typeset -p 

In Bash, identical to declare. See declare.

In the Korn shell, assign a type to each variable (along with an optional initial value), or, if no variables are supplied, display all variables of a particular type (as determined by the options). When variables are specified, -option enables the type, and +option disables it. With no variables, -option prints variable names and values; +option prints only the names.

The second form shown is specific to ksh93.

Options


-A arr

arr is an associative array. ksh93 only.


-b

The variable can hold any data, including binary data. References retrieve the value printed in base-64 notation; The %B format with printf may be used to print the value. ksh93 only.


-E d

variable is a floating-point number. d is the number of decimal places. The value is printed using printf %g format. ksh93 only.


-f[c]

The named variable is a function; no assignment is allowed. If no variable is given, list current function names. Flag c can be t, u, or x. t turns on tracing (same as set -x). u marks the function as undefined, which causes autoloading of the function (i.e., a search of FPATH locates the function when it's first used. ksh93 also searches PATH). In ksh88, x exports the function. In ksh93, x is accepted but does nothing. Note the aliases autoload and functions.


-F d

variable is a floating-point number. d is the number of decimal places. The value is printed using printf %f format. ksh93 only.


-H

On non-Unix systems, map Unix filenames to host filenames.


-i[n]

Define variables as integers of base n. integer is an alias for typeset -i.


-L[n]

Define variables as left-justified strings, n characters long (truncate or pad with blanks on the right as needed). Leading blanks are stripped; leading zeroes are stripped if -Z is also specified. If no n is supplied, field width is that of the variable's first assigned value.


-l

Convert uppercase to lowercase.


-n

variable is an indirect reference to another variable (a nameref ). ksh93 only. (See the Variables," section, earlier in this chapter.)


-p

Print typeset commands to re-create the types of all the current variables. ksh93 only.


-R[n]

Define variables as right-justified strings, n characters long (truncate or pad with blanks on the left as needed). Trailing blanks are stripped. If no n is supplied, field width is that of the variable's first assigned value.


-r

Mark variables as read-only. See also readonly.


-t

Mark variables with a user-definable tag.


-u

Convert lowercase to uppercase.


-ui[n]

Define variables as unsigned integers of base n. ksh93 only.


-x

Mark variables for automatic export.


-Z[n]

When used with -L, strip leading zeroes. When used alone, it's similar to -R, except that -Z pads numeric values with zeroes and pads text values with blanks.

Examples

     typeset                 List name, value, and type of all set variables     typeset -x              List names and values of exported variables     typeset +r PWD          End read-only status of PWD     typeset -i n1 n2 n3     Three variables are integers     typeset -R5 zipcode     zipcode is flush right, five characters wide 

ulimit

     ulimit [options] [n] 

Print the value of one or more resource limits, or, if n is specified, set a resource limit to n. Resource limits can be either hard (-H) or soft (-S). By default, ulimit sets both limits or prints the soft limit. The options determine which resource is acted on.

Options


-H

Hard limit. Anyone can lower a hard limit; only privileged users can raise it.


-S

Soft limit. Must be lower than the hard limit.


-a

Print all limits.


-b

Size of socket buffers. ksh93 only.


-c

Maximum size of core files.


-d

Maximum kilobytes of data segment or heap.


-f

Maximum size of files (the default option).


-l

Maximum size of address space that can be locked in memory. Not ksh88.


-L

Maximum number of file locks. ksh93 only.


-m

Maximum kilobytes of physical memory. (Not effective on all Unix systems.)


-M

Maximum size of the address space. ksh93 only.


-n

Maximum number of file descriptors.


-p

Size of pipe buffers. (Not effective on all Unix systems.)


-s

Maximum kilobytes of stack segment.


-t

Maximum CPU seconds.


-T

Maximum number of threads. ksh93 only.


-u

Maximum number of processes a single user can have.


-v

Maximum kilobytes of virtual memory.

umask

     umask [nnn]     umask [-pS] [mask] 

Display file creation mask or set file creation mask to octal value nnn. The file creation mask determines which permission bits are turned off (e.g., umask 002 produces rw-rw-r--). See the entry in Chapter 3 for examples.

The second form is not in ksh88. A symbolic mask is permissions to keep.

Option


-p

Output is in a form that can be reread later by the shell. Bash only.


-S

Print the current mask using symbolic notation. Not ksh88.

unalias

     unalias namesunalias -a 

Remove names from the alias list. See also alias.

Option


-a

Remove all aliases. Not ksh88.

unset

     unset [options] names 

Erase definitions of functions or variables listed in names.

Options


-f

Unset functions names.


-n

Unset indirect variable (nameref) name, not the variable the nameref refers to. ksh93 only.


-v

Unset variables names (default). Not ksh88.

until

     until conditiondo      commandsdone 

Until condition is met, do commands. condition is often specified with the test command. See the Examples under case and test.

wait

     wait [ID] 

Pause in execution until all background jobs complete (exit status 0 is returned), or pause until the specified background process ID or job ID completes (exit status of ID is returned). Note that the shell variable $! contains the process ID of the most recent background process.

Example

     wait $!   Wait for most recent background process to finish 

whence

     whence [options] commands 

Korn shell only. Show whether each command name is a Unix command, a built-in command, a defined shell function, or an alias.

Options


-a

Print all interpretations of commands. ksh93 only.


-f

Skip the search for shell functions. ksh93 only.


-p

Search for the pathname of commands.


-v

Verbose output.

while

     while conditiondo      commands     done 

While condition is met, do commands. condition is often specified with the test command. See the Examples under case and test.



Linux in a Nutshell
Linux in a Nutshell
ISBN: 0596154488
EAN: 2147483647
Year: 2004
Pages: 147

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