5.9. Built-in Commands

 < Day Day Up > 

@

         @ variable = expression         @ variable[n] = expression         @

Assign the value of the arithmetic expression to variable, or to the nth element of variable if the index n is specified. With no variable or expression specified, print the values of all shell variables (same as set). Expression operators as well as examples are listed under the section "Expressions," earlier in this chapter. Two special forms are also valid:


@ variable++


@ variable[ n]++

Increment variable or element by 1.


@ variable--


@ variable[ n]--

Decrement variable or element by 1.

#

     #

Ignore all text that follows on the same line. # is used in shell scripts as the comment character and is not really a command. In addition, a file that has # as its first character is sometimes interpreted by older systems as a C shell script.

#!

     #! shell

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 around 32 characters on the maximum length of shell. Any program that interprets input may be used for shell, such as awk or Perl. For example:

     #! /bin/tcsh   -f

:

     :

Null command. Returns an exit status of 0. The colon command is often put as the first character of a Bourne or Korn shell script to act as a place-holder to keep a # (hash) from accidentally becoming the first character.

alias

     alias [name [command]]

Assign name as the shorthand name, or alias, for command. If command is omitted, print the alias for name; if name also is omitted, print all aliases. Aliases can be defined on the command line, but more often they are stored in .tcshrc so that they take effect upon logging in. (See the section "Sample .tcshrc File" earlier in this chapter.) Alias definitions can reference command-line arguments, much like the history list. Use \!* to refer to all command-line arguments, \!^ for the first argument, \!\!:2 for the second, \!$ for the last, and so on. An alias name can also be any valid Unix command except alias or unalias; however, you lose the original command's meaning unless you type \name. See also unalias and the earlier section "Special Aliases."

Examples

Set the size for xterm windows under the X Window System:

     alias R 'set noglob; eval 'resize'; unset noglob'

Show aliases that contain the string "ls":

     alias | grep ls

Run nroff on all command-line arguments:

     alias ms 'nroff -ms \!*'

Copy the file that is named as the first argument:

     alias back 'cp \!^ \!^.old'

Use the regular ls, not its alias:

     % \ls

alloc

     alloc

Print total amount of used and free memory.

bg

     bg [jobIDs]

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

Example

To place a time-consuming process in the background, you might begin with:

     4% nroff -ms report | col > report.txt     CTRL-Z

and then issue any one of the following:

     5% bg      5% bg %         Current job     5% bg %1        Job number 1     5% bg %nr       Match initial string nroff     5% % & 

bindkey

     bindkey [options] [key] [command]

Display all key bindings, or bind a key to an editor command.

Options


-a

List standard and alternate key bindings.


-b key

Expect key to be one of the following: a control character (in hat notation, e.g., ^B, or C notation, e.g., C-B); a metacharacter (e.g., M-B); a function key (e.g., F-string); or an extended prefix key (e.g., X-B).


-c command

Interpret command as a shell command, not as an editor command.


-d key

Bind key to its original binding.


-e

Bind to standard Emacs bindings.


-k key

Expect key to refer to an arrow (left, right, up, or down).


-l

List and describe all editor commands.


-r key

Completely unbind key.


-s

Interpret command as a literal string and treat as terminal input.


-u

Print usage message.


-v

Bind to standard vi bindings.


--

End option processing. The following item is treated as a key, even if it looks like an option.

break

     break

Resume execution following the end command of the nearest enclosing while or foreach.

breaksw

     breaksw

Break from a switch; continue execution after the endsw.

built-ins

     built-ins

Print all built-in shell commands.

bye

     bye

Same as logout. Must have been compiled into the shell; see the version variable.

case

     case pattern:

Identify a pattern in a switch.

cd

     cd [options] [dir]

Change working directory to dir; default is home directory of user. If dir is a relative pathname but is not in the current directory, the cdpath variable is searched. See the section "Sample .tcshrc File" earlier in this chapter.

Options


-

Change to previous directory. (Compare to popd, which manipulates the directory stack.)


-l

Explicitly expand ~ notation; implies -p.


-n

Wrap entries before end-of-line; implies -p.


-p

Print directory stack.


-v

Print entries one per line; implies -p.

chdir

     chdir [dir]

Same as cd. Useful if you are redefining cd as an alias.

complete

     complete [string [word/pattern/list[:select]/[suffix]]]

List all completions, or, if specified, all completions for string (which may be a pattern). Further options can be specified.

Options for word

c

Complete current word only, without referring to pattern.

C

Complete current word only, referring to pattern.

n

Complete previous word.

N

Complete word before previous word.

p

Expect pattern to be a range of numbers. Perform completion within that range.


Options for list

Various lists of strings can be searched for possible completions. Some list options include:

(string)

Members of the list string.

$variable

Words from variable.

'command'

Output from command.

a

Aliases.

b

Bindings.

c

Commands.

C

External (not built-in) commands.

d

Directories.

D

Directories whose names begin with string.

e

Environment variables.

f

Filenames.

F

Filenames that begin with string.

g

Groups.

j

Jobs.

l

Limits.

n

Nothing.

s

Shell variables.

S

Signals.

t

Text files.

T

Text files whose names begin with string.

u

Users.

v

Any variables.

x

Like n, but prints select as an explanation with the editor command list-choices.

X

Completions.


select

select should be a glob pattern. Completions are limited to words that match this pattern. suffix is appended to all completions.

continue

     continue

Resume execution of nearest enclosing while or foreach.

default

     default:

Label the default case (typically last) in a switch.

dirs

     dirs [options]

Print the directory stack, showing the current directory first. See also popd and pushd.

Options


-c

Clear the directory stack.


-l

Expand the home directory symbol (~) to the actual directory name.


-L file

Recreate stack from file, which should have been created by dirs -S file.


-n

Wrap output.


-S file

Print to file a series of pushd and popd commands that can be invoked to replicate the stack.


-v

Print one directory per line.

echo

     echo [-n] string

Write string to standard output; if -n is specified, the output is not terminated by a newline. Set the echo_style shell variable to emulate BSD and/or System V echo flags and escape sequences. See also echo in Chapter 2 and Chapter 4.

echotc

     echotc [options] arguments

Display terminal capabilities or move cursor on screen, depending on the argument.

Options


-s

Return empty string, not error, if capability doesn't exist.


-v

Display verbose messages.

Arguments

baud

Display current baud rate.

cols

Display current column.

cm column row

Move cursor to specified coordinates.

home

Move cursor to home position.

lines

Print number of lines per screen.

meta

Does this terminal have meta capacity (usually the Alt key)?

tabs

Does this terminal have tab capacity?


else

     else

Reserved word for interior of if ... endif statement.

end

     end

Reserved word that ends a foreach or while statement.

endif

     endif

Reserved word that ends an if statement.

endsw

     endsw

Reserved word that ends a switch statement.

eval

     eval args

Typically, eval is used in shell scripts, and args is a line of code that may contain 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.) A Bourne shell example can be found under eval in Chapter 4. A tcsh example of eval can be found under alias. Other uses of eval are shown next.

Examples

The following lines can be placed in the .login file to set up terminal characteristics:

     set noglob     eval 'tset -s xterm'     unset noglob

The following commands show the effect of eval:

     % set b='$a'      % set a=hello      % echo $b            Read the command line once     $a     % eval echo $b       Read the command line twice     hello

exec

     exec command [args ...]

Execute command in place of current shell. This terminates the current shell, rather than creating a new process under it.

exit

     exit [expr]

Exit a shell script with the status given by expr. A status of zero means success; nonzero means failure. If expr is not specified, the exit value is that of the status variable. exit can be issued at the command line to close a window (log out).

fg

     fg [jobIDs]

Bring the current job or the jobIDs to the foreground. jobID can be %job-number. See also the section "Job Control" earlier in this chapter.

Example

If you suspend a vi editing session (by pressing CTRL-Z), you might resume vi using any of these commands:

     % %      % fg      % fg %      % fg %vi       Match initial string

filetest

     filetest -op files

Apply op file-test operator to files. Print results in a list. See the section "File inquiry operators" earlier in this chapter for the list of file-test operators.

foreach

     foreach name (wordlist)      commands     end

Assign variable name to each value in wordlist and execute commands between foreach and end. You can use foreach as a multiline command issued at the shell prompt (first of the following examples), or you can use it in a shell script (second example).

Examples

Rename all files that begin with a capital letter:

     % foreach i ([A-Z]*)     foreach? mv $i $i.old     foreach? end

Check whether each command-line argument is an option or not:

     foreach arg ($argv)        # does it begin with - ?        if ("$arg" =~ -*) then           echo "Argument is an option"        else           echo "Argument is a filename"        endif     end

glob

     glob wordlist

Do filename, variable, and history substitutions on wordlist. This expands it much like echo, except that no \ escapes are recognized, and words are delimited by null characters. glob is typically used in shell scripts to "hardcode" a value so that it remains the same for the rest of the script.

goto

     goto string

Skip to a line whose first nonblank word is string followed by a colon, and continue execution below that line. On the goto line, string can be a variable or filename pattern, but the label branched to must be a literal, expanded value and must not occur within a foreach or while.

hashstat

     hashstat

Display statistics that show the hash table's level of success at locating commands via the path variable.

history

     history [options]

Display the list of history events. (History syntax is discussed earlier in the section "Command History.")

Note: multiline compound commands such as foreach ... end are not saved in the history list. In general, the interactive command-line editing facilities are preferable to those of history and history substitution with the ! character.

Options


n

Display only the last n history commands, instead of the number set by the history shell variable.


-c

Clear history list.


-h

Print history list without event numbers.


-L file

Append the list of saved history commands in file to the history list.


-M file

Merge the current history list and the history list in file, sorted by time.


-r

Print in reverse order; show oldest commands last.


-S file

Save the history list to file. See also the savehist variable.


-T

Print with timestamp.

Example

To save and execute the last five commands:

     history -h 5 > do_it     source do_it

hup

     hup [command]

Start command but make it exit when sent a hangup signal, which is sent when shell exits. With no arguments, set the shell to exit on hangup signal. This latter form is allowed only in scripts.

if

     if

Begin a conditional statement. The simple format is:

     if (expr) cmd

There are three other possible formats, shown side by side:

     if (expr) then   if (expr) then   if (expr) then        cmds             cmds1             cmds1     endif            else             else if (expr) then                         cmds2             cmds2                      endif            else                                           cmds3                                       endif

In the simplest form, execute cmds if expr is true, otherwise do nothing. (Even if expr is false, any redirection in cmd still occurs; this is a bug.) In the other forms, execute one or more commands. If expr is true, continue with the commands after then; if expr is false, branch to the commands after else or else if and continue checking. For more examples, see the section "Expressions" earlier in this chapter, or the shift or while commands.

Example

Take a default action if no command-line arguments are given:

     if ($#argv == 0) then        echo "No filename given. Sending to Report."        set outfile = Report     else        set outfile = $argv[1]     endif

jobs

     jobs [-l]

List all running or stopped jobs; -l includes process IDs. For example, you can check whether a long compilation or text format is still running. Also useful before logging out.

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 is similar to the external kill command described in Chapter 2 but also allows symbolic job names. See the kill entry in Chapter 2 for a list of commonly available signals and for the header files where the corresponding signal numbers may be found. Stubborn processes can be killed using signal 9. See also the earlier section "Job Control."

Options


-l

List the signal names. (Used by itself.)


- signal, -s signal

Send the given signal to the jobs specified by IDs. The signal is either a signal number, or a signal name without the SIG prefix (e.g., HUP, not SIGHUP).

Examples

If you've issued the following command:

     44% nroff -ms report > report.txt &      [1] 19536                tcsh prints job and process IDs

you can terminate it in any of the following ways:

     45% kill 19536            Process ID     45% kill %                Current job     45% kill %1               Job number 1     45% kill %nr              Initial string     45% kill %?report         Matching string

limit

     limit [-h] [resource [limit]]

Display limits or set a limit on resources used by the current process and by each process it creates. If no limit is given, the current limit is printed for resource. If resource also is omitted, all limits are printed. By default, the current soft limits are shown or set; with -h, hard limits are used. A soft limit may be increased or decreased without requiring special privileges. A hard limit imposes an absolute limit that can't be exceeded. Only a privileged user may raise it. See also unlimit.

Option


-h

Use hard, not soft, limits.

Resources

concurrency

Maximum number of per-process threads. Not available on all systems.

coredumpsize

Maximum size of a core dump file.

cputime

Maximum number of seconds the CPU can spend; can be abbreviated as cpu.

datasize

Maximum size of data (including stack).

descriptors

Maximum number of open files.

filesize

Maximum size of any one file.

maxproc

Maximum number of processes.

memorylocked

Maximum size a process can lock into memory.

memoryuse

Maximum amount of physical memory that can be allocated to a process.

sbsize

Maximum size of a socket buffer. Not available on all systems.

stacksize

Maximum size of stack.

vmemoryuse

Maximum amount of virtual memory that can be allocated to a process.


Limit

A number followed by an optional character (a unit specifier).

For cputime:

nh (for n hours)

 

nm (for n minutes)

 

mm:ss (minutes and seconds)

For others:

nk (for n kilobytes, the default)

 

nm (for n megabytes)


log

     log

Consult the watch variable for list of users being watched. Print list of those who are presently logged in.

login

     login [options] [user]

Replace a login shell with /bin/login. See the entry for login in Chapter 2 and your system's login manpage.

logout

     logout

Terminate the login shell.

ls-F

     ls-F [options] [files]

Faster alternative to ls -F. If given any options, invokes ls. See also the listlinks variable.

newgrp

     newgrp [-] [group]

Change user's group ID to specified group ID or, if none is specified, to original group ID. If - is entered as an option, reset environment as if user had logged in with new group. Must have been compiled into the shell; see the version variable.

nice

     nice [±n] command

Change the execution priority for command or, if none is given, change priority for the current shell. (See also nice in Chapter 2.) The priority range is -20 to 19, with a default of 4. The range is backwards from what you might expect: -20 gives the highest priority (fastest execution); 19 gives the lowest. Only a privileged user may specify a negative number.


+ n

Add n to the priority value (lower job priority).


- n

Subtract n from the priority value (raise job priority). Privileged users only.

nohup

     nohup [command]

"No hangup signals." Do not terminate command after terminal line is closed (i.e., when you hang up from a phone or log out). Use without command in shell scripts to keep script from being terminated. (See also nohup in Chapter 2.)

notify

     notify [jobID]

Report immediately when a background job finishes (instead of waiting for you to exit a long editing session, for example). If no jobID is given, the current background job is assumed.

onintr

     onintr label     onintr -     onintr

"On interrupt." Used in shell scripts to handle interrupt signals (similar to the TRap 2 and TRap "" 2 commands in the Bourne shell). The first form is like a goto label. The script will branch to label: if it catches an interrupt signal (e.g., CTRL-C). The second form lets the script ignore interrupts. This is useful at the beginning of a script or before any code segment that needs to run unhindered (e.g., when moving files). The third form restores interrupt handling previously disabled with onintr -.

Example

onintr cleanup     Go to "cleanup" on interrupt      .      .                 Shell script commands      .     cleanup:           Label for interrupts       onintr -         Ignore additional interrupts       rm -f $tmpfiles  Remove any files created       exit 2           Exit with an error status

popd

     popd [options]

Remove the current entry from the directory stack or remove the n th entry from the stack. The current entry has number zero and appears on the left. See also dirs and pushd.

Options


+ n

Specify nth entry.


-l

Expand ~ notation.


-n

Wrap long lines.


-p

Override the pushdsilent shell variable, which otherwise prevents the printing of the final stack.


-v

Print precisely one directory per line.

printenv

     printenv [variable]

Print all (or one specified) environment variables and their values.

pushd

     pushd [options] name     pushd [options] +n     pushd

The first form changes the working directory to name and adds it to the directory stack. The second form rotates the nth entry to the beginning, making it the working directory. (Entry numbers begin at zero.) With no arguments, pushd switches the first two entries and changes to the new current directory.

The -l, -n, and -v options behave the same as in popd. See also dirs and popd.

Examples

% dirs      /home/bob /usr     % pushd /etc             Add /etc to directory stack     /etc /home/bob /usr     % pushd +2               Switch to third directory     /usr /etc /home/bob     % pushd                  Switch top two directories     /etc /usr /home/bob     % popd                   Discard current entry; go to next     /usr /home/bob

rehash

     rehash

Recompute the internal hash table for the path variable. Use rehash whenever a new command is created during the current session. This allows the path variable to locate and execute the command. (If the new command resides in a directory not listed in path, add the directory to path before rehashing.) See also unhash.

repeat

     repeat n command

Execute n instances of command.

Examples

Generate a test file for a program by saving 25 copies of /usr/dict/words in a file:

     % repeat 25 cat /usr/dict/words > test_file

Read 10 lines from the terminal and store in item_list:

     % repeat 10 line > item_list

Append 50 boilerplate files to report:

     % repeat 50 cat template >> report

sched

     sched [options]     sched time command

Without options, print all scheduled events. The second form schedules an event. time should be specified in hh:mm form (e.g., 13:00).

Options


+hh:mm

Schedule event to take place hh:mm from now.


-n

Remove n th item from schedule.

set

     set [-r] variable = value     set [-r] variable[n] = value     set [-f | -l] variable=(list)     set [-r] variable     set [-r]

Set variable to value or, if multiple values are specified, set the variable to the list of words in the value list. If an index n is specified, set the n th word in the variable to value. (The variable must already contain at least that number of words.) If only variable is specified, set the variable to null. With no arguments, display the names and values of all set variables. See also the section "Predefined Shell Variables," earlier in this chapter. Only one of -f or -l can be given.

Options


-f

When setting a variable to a list, remove duplicate words from the list, keeping only the first occurrence of a duplicate.


-l

When setting a variable to a list, remove duplicate words from the list, keeping only the last occurrence of a duplicate.


-r

List only read-only variables, or set specified variable to read-only.

Examples

% set list=(yes no maybe)       Assign a wordlist     % set list [3 ]=maybe             Assign an item in existing wordlist     % set quote="Make my day"      Assign a variable     % set x=5 y=10 history=100      Assign several variables     % set blank                     Assign a null value to blank

setenv

     setenv [name [value]]

Assign a value to an environment variable name. By convention, name should be uppercase. value can be a single word or a quoted string. If no value is given, the null value is assigned. With no arguments, display the names and values of all environment variables. A number of environment variables are automatically exported from the corresponding shell variables; see the earlier section "Environment Variables."

settc

     settc capability value

Set terminal capability to value.

setty

     setty [options] [±mode]

Do not allow shell to change specified tty modes. There are three sets of modes, edit, quote, and execute. By default, act on the execute set.

Options


+ mode

Without arguments, list all modes in specified set that are on. Otherwise, turn on specified mode.


- mode

Without arguments, list all modes in specified set that are off. Otherwise, turn off specified mode.


-a

List all modes in specified set.


-d

Act on the edit set of modes (used when editing commands).


-q

Act on the quote set of modes (used when entering characters verbatim).


-x

Act on the execute set of modes (used when executing commands). This is the default.

shift

     shift [variable]

If variable is given, shift the words in a word list variable; e.g., assuming a wordlist variable named offices, offices[2] becomes offices[1]. With no argument, shift the positional parameters (command-line arguments); i.e., $2 becomes $1. shift is typically used in a while loop. See additional example under while.

Example

while ($#argv)      While there are arguments         if (-f $argv[1])            wc -l $argv[1]         else            echo "$argv[1] is not a regular file"         endif         shift           Get the next argument     end

source

     source [-h] script [args]

Read and execute commands from a shell script. With -h, the commands are added to the history list but aren't executed. Arguments can be passed to the script and are put in argv.

Example

% source ~/.tcshrc

stop

     stop jobIDs

Stop the background jobs specified by jobIDs; this is the complement of CTRL-Z or suspend.

suspend

     suspend

Suspend the current foreground job; similar to CTRL-Z. Often used to stop an su command.

switch

     switch

Process commands depending on a string value. When you need to handle more than three choices, switch is a useful alternative to an if-then-else statement. If the string matches pattern1, the first set of commands executes; if string matches pattern2, the second set of commands executes; and so on. If no patterns match, the set of commands under the default case executes. string can be specified using command substitution, variable substitution, or filename expansion. Patterns can be specified using the pattern-matching symbols *, ?, [, and ]. breaksw exits the switch after commands are executed. If breaksw is omitted (which is rarely done), the switch continues to execute another set of commands until it reaches a breaksw or endsw. Here is the general syntax of switch, side-by-side with an example that processes the first command-line argument.

     switch (string)       switch ($argv[1])       case pattern1:        case -[nN]:           commands              nroff $file | lp           breaksw               breaksw       case pattern2:        case -[Pp]:           commands              pr $file | lp           breaksw               breaksw       case pattern3:        case -[Mm]:           commands              more $file           breaksw               breaksw           .                 case -[Ss]:           .                     sort $file           .                     breaksw       default:              default:           commands              echo "Error no such option"                                 exit 1           breaksw               breaksw     endsw                 endsw

telltc

     telltc

Print all terminal capabilities and their values.

termname

     termname [termtype]

Check the termcap or terminfo database to see if termtype exists. With no argument, use the current value of the TERM variable. This command prints the termtype to standard output and returns zero if the terminal type is found in the database, one otherwise.

time

     time [command]

Execute a command and show how much time it uses. With no argument, time can be used in a shell script to time the script.

umask

     umask [nnn]

Display file-creation mask or set file-creation mask to octal nnn. The file-creation mask determines which permission bits are turned off. With no nnn, print the current mask. See the umask entry in Chapter 2 for examples.

unalias

     unalias pattern

Remove all aliases whose names match pattern from the alias list. See alias for more information.

uncomplete

     uncomplete pattern

Remove completions (specified by complete) whose names match pattern.

unhash

     unhash

Stop using the internal hash table. The shell stops using hashed values and searches the path directories to locate a command. See also rehash.

unlimit

     unlimit [-h] [resource]

Remove the allocation limits on resource. If resource is not specified, remove limits for all resources. See limit for more information. With -h, remove hard limits. Removing hard limits can be done only by a privileged user.

unset

     unset variables

Remove one or more variables. Variable names may be specified as a pattern, using filename metacharacters. Does not remove read-only variables. See set.

unsetenv

     unsetenv variables

Remove one or more environment variables. Variable names may be specified as a pattern, using filename metacharacters. See setenv.

wait

     wait

Pause in execution until all child processes complete, or until an interrupt signal is received.

watchlog

     watchlog

Same as log. Must have been compiled into the shell; see the version shell variable.

where

     where command

Display all aliases, built-in commands, and executables named command found in the path.

which

     which command

Report which version of command will be executed. Same as the external executable which, but faster, and checks tcsh built-ins.

while

     while (expression)      commands     end

As long as expression is true (evaluates to nonzero), evaluate commands between while and end. break and continue can be used to terminate or continue the loop. See also the example under shift.

Example

set user = (alice bob carol ted)     while ($argv[1] != $user[1])        Cycle through each user, checking for a match        shift user        If we cycled through with no match...        if ($#user == 0) then          echo "$argv[1] is not on the list of users"          exit 1        endif     end

     < Day Day Up > 


    Unix in a Nutshell
    Unix in a Nutshell, Fourth Edition
    ISBN: 0596100299
    EAN: 2147483647
    Year: 2005
    Pages: 201

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