United States-English |
|
|
HP-UX Reference > Ccsh(1)HP-UX 11i Version 3: February 2007 |
|
NAMEcsh — a shell (command interpreter) with C-like syntax DESCRIPTIONcsh is a command language interpreter that incorporates a command history buffer, C-like syntax, and job control facilities. Command OptionsCommand options are interpreted as follows:
After processing the command options, if arguments remain in the argument list, and the -c, -i, -s, or -t options were not specified, the first remaining argument is taken as the name of a file of commands to be executed. COMMANDSA simple command is a sequence of words, the first of which specifies the command to be executed. A sequence of simple commands separated by vertical bar (|) characters forms a pipeline. The output of each command in a pipeline becomes the input for the next command in the pipeline. Sequences of pipelines can be separated by semicolons (;) which causes them to be executed sequentially. A sequence of pipelines can be executed in background mode by adding an ampersand character (&) after the last entry. Any pipeline can be placed in parentheses to form a simple command which, in turn, can be a component of another pipeline. Pipelines can also be separated by || or && indicating, as in the C language, that the second pipeline is to be executed only if the first fails or succeeds, respectively. Jobscsh associates a job with each pipeline and keeps a table of current jobs (printed by the jobs command) and assigns them small integer numbers. When a job is started asynchronously using &, the shell prints a line resembling:
indicating that the job which was started asynchronously was job number 1 and had one (top-level) process, whose process id was 1234. If you are running a job and want to do something else, you can type the currently defined suspend character (see termio(7)) which sends a stop signal to the current job. csh then normally indicates that the job has been `Stopped', and prints another prompt. You can then manipulate the state of this job, putting it in the background with the bg command, run some other commands, and then eventually bring the job back into the foreground with the foreground command fg. A suspend takes effect immediately and is like an interrupt in that pending output and unread input are discarded when it is typed. There is a delayed suspend character which does not generate a stop signal until a program attempts to read(2) it. This can usefully be typed ahead when you have prepared some commands for a job which you want to stop after it has read them. A job being run in the background stops if it tries to read from the terminal. Background jobs are normally allowed to produce output, but this can be disabled by giving the command stty tostop (see stty(1)). If you set this tty option, background jobs stop when they try to produce output, just as they do when they try to read input. Keyboard signals and line-hangup signals from the terminal interface are not sent to background jobs on such systems. This means that background jobs are immune to the effects of logging out or typing the interrupt, quit, suspend, and delayed suspend characters (see termio(7)). There are several ways to refer to jobs in the shell. The character % introduces a job name. If you wish to refer to job number 1, you can name it as %1. Just naming a job brings it to the foreground; thus %1 is a synonym for fg %1, bringing job 1 back into the foreground. Similarly, typing %1 & resumes job 1 in the background. Jobs can also be named by prefixes of the string typed in to start them if these prefixes are unambiguous; thus %ex normally restarts a suspended ex(1) job, if there is only one suspended job whose name begins with the string ex. It is also possible to say %?string which specifies a job whose text contains string, if there is only one such job. csh maintains a notion of the current and previous jobs. In output pertaining to jobs, the current job is marked with a + and the previous job with a -. The abbreviation %+ refers to the current job and %- refers to the previous job. For close analogy with the syntax of the history mechanism (described below), %% is also a synonym for the current job. csh learns immediately whenever a process changes state. It normally informs you whenever a job becomes blocked so that no further progress is possible, but only just before printing a prompt. This is done so that it does not otherwise disturb your work. If, however, you set the shell variable notify, csh notifies you immediately of changes in status of background jobs. There is also a csh built-in command called notify which marks a single process so that any status change is immediately reported. By default, notify marks the current process. Simply type notify after starting a background job to mark it. If you try to leave the shell while jobs are stopped, csh sends the warning message: You have stopped jobs. Use the jobs command to see what they are. If you do this or immediately try to exit again, csh does not warn you a second time, and the suspended jobs are terminated (see exit(2)). Built-In CommandsBuilt-in commands are executed within the shell without spawning a new process. If a built-in command occurs as any component of a pipeline except the last, it is executed in a subshell. The built-in commands are:
Non-Built-In Command ExecutionWhen a command to be executed is not a built-in command, csh attempts to execute the command via exec(2). Each word in the variable path names a directory in which the shell attempts to find the command (if the command does not begin with /). If neither -c nor -t is given, the shell hashes the names in these directories into an internal table so that an exec is attempted only in those directories where the command might possibly reside. This greatly speeds command location when a large number of directories are present in the search path. If this mechanism has been turned off (via unhash), or if -c or -t was given, or if any directory component of path does not begin with a /, the shell concatenates the directory name and the given command name to form a path name of a file which it then attempts to execute. Commands placed inside parentheses are always executed in a subshell. Thus (cd ; pwd) prints the home directory then returns to the current directory upon completion, whereas: cd ; pwd remains in the home directory upon completion. When commands are placed inside parentheses, it is usually to prevent chdir from affecting the current shell. If the file has execute permissions but is not an executable binary file, it is assumed to be a script file, which is a file of data for an interpreter that is executed as a separate process. csh first attempts to load and execute the script file (see exec(2)). If the first two characters of the script file are #!, exec(2) expects an interpreter path name to follow and attempts to execute the specified interpreter as a separate process to read the entire script file. If no #! interpreter is named, and there is an alias for the shell, the words of the alias are inserted at the beginning of the argument list to form the shell command. The first word of the alias should be the full path name of the command to be used. Note that this is a special, late-occurring case of alias substitution, which inserts words into the argument list without modification. If no #! interpreter is named and there is no shell alias, but the first character of the file is #, the interpreter named by the $shell variable is executed (note that this normally would be /usr/bin/csh, unless the user has reset $shell). If $shell is not set, /usr/bin/csh is executed. If no !# interpreter is named, and there is no shell alias, and the first character of the file is not #, /usr/bin/sh is executed to interpret the script file. History SubstitutionsHistory substitutions enable you to repeat commands, use words from previous commands as portions of new commands, repeat arguments of a previous command in the current command, and fix spelling or typing mistakes in an earlier command. History substitutions begin with an exclamation point (!). Substitutions can begin anywhere in the input stream, but cannot be nested. The exclamation point can be preceded by a backslash to cancel its special meaning. For convenience, an exclamation point is passed to the parser unchanged when it is followed by a blank, tab, newline, equal sign, or left parenthesis. Any input line that contains history substitution is echoed on the terminal before it is executed for verification. Commands input from the terminal that consist of one or more words are saved on the history list. The history substitutions reintroduce sequences of words from these saved commands into the input stream. The number of previous commands saved is controlled by the history variable. The previous command is always saved, regardless of its value. Commands are numbered sequentially from 1. You can refer to previous events by event number (such as !10 for event 10), relative event location (such as !-2 for the second previous event), full or partial command name (such as !d for the last event using a command with initial character d), and string expression (such as !?mic? referring to an event containing the characters mic). These forms, without further modification, simply reintroduce the words of the specified events, each separated by a single blank. As a special case, !! is a re-do; it refers to the previous command. To select words from a command, use a colon (:) and a designator for the desired words after the event specification. The words of an input line are numbered from zero. The basic word designators are:
The colon separating the command specification from the word designator can be omitted if the argument selector begins with a ^, $, *, -, or %. After word designator can be followed by a sequence of modifiers, each preceded by a colon. The following modifiers are defined:
Unless preceded by a g, the modification is applied only to the first modifiable word. An error results if a substitution is attempted and cannot be completed (i.e., if you ask for a substitution of !11 on a history buffer containing only 10 commands). The left hand side of substitutions are strings; not regular expressions in the sense of HP-UX editors. Any character can be used as the delimiter in place of a slash (/). Use a backslash to quote a delimiter character if it is used in the l or r string. The character & in the right-hand side is replaced by the text from the left. A \ also quotes &. A null l string uses the previous string either from an l or from a contextual scan string s in !?s?. The trailing delimiter in the substitution can be omitted if a new-line character follows immediately, as may the trailing ? in a contextual scan. A history reference can be given without an event specification (as in !$). In this case, the reference is to the previous command unless a previous history reference occurred on the same line, in which case this form repeats the previous reference. Thus !?foo?^ !$ gives the first and last arguments from the command matching ?foo?. A special abbreviation of a history reference occurs when the first non-blank character of an input line is a circumflex (^). This is equivalent to !:s^, providing a convenient shorthand for substitutions on the text of the previous line. Thus ^lb^lib fixes the spelling of lib in the previous command. Finally, a history substitution can be enclosed within curly braces { } if necessary to insulate it from the characters which follow. Thus, after ls -ld ~paul one could execute !{l}a to do ls -ld ~paula while !la would look for a command starting with la. Quoting with Single and Double QuotesThe quotation of strings by single quotes (') and double quotes (") can be used to prevent all or some of the remaining substitutions. Strings enclosed in single quotes are protected from any further interpretation. Strings enclosed in double quotes are still variable- and command-expanded as described below. In both cases the resulting text becomes (all or part of) a single word. Only in one special case (see Command Substitution below) does a double-quoted string yield parts of more than one word; single-quoted strings never do. Alias Substitutioncsh maintains a list of aliases that can be established, displayed, and modified by the alias and unalias commands. After a command line is scanned, it is parsed into distinct commands and the first word of each command, left-to-right, is checked to see if it has an alias. If it does, the text which is the alias for that command is reread with the history mechanism available as if that command was the previous input line. The resulting words replace the command and argument list. If no reference is made to the history list, the argument list is left unchanged. Thus, if the alias for ls is ls -l, the command ls /usr maps to ls -l /usr, leaving the argument list undisturbed. Similarly, if the alias for lookup was grep !^ /etc/passwd, lookup bill maps to grep bill /etc/passwd . If an alias is found, the word transformation of the input text is performed and the aliasing process begins again on the re-formed input line. Looping is prevented if the first word of the new text is the same as the old by flagging it to prevent further aliasing. Other loops are detected and cause an error. Note that the mechanism allows aliases to introduce parser metasyntax. Thus: alias print 'pr \!* | lp' makes a command that uses pr(1) to print its arguments on the line printer. ExpressionsSome of the built-in commands take expressions in which the operators are similar to those of C, with the same precedence. These expressions appear in the @, exit, if, and while commands. The following operators are available (shown in order of increasing precedence): || && | ^ & == != =~ !~ <= >= < > << >> + - * / % ! ~ ( ) The following list shows the grouping of these operators. The precedence decreases from top to bottom in the list:
The operators ==, !=, =~, and !~ compare their arguments as strings; all others operate on numbers. The operators =~ and !~ are similar to != and ==, except that the right-hand side is a pattern (containing *s, ?s, and instances of [...]) against which the left hand operand is matched. This reduces the need for use of the switch statement in shell scripts when all that is really needed is pattern matching. Strings beginning with 0 are considered octal numbers. Null or missing arguments are considered 0. The result of all expressions are strings that represent decimal numbers. It is important to note that no two components of an expression can appear in the same word. These components should be surrounded by spaces except when adjacent to components of expressions that are syntactically significant to the parser: -, &, |, <, >, (, and ). Also available in expressions as primitive operands are command executions enclosed in curly braces ({ }) and file enquiries of the form -l filename, where l is one of:
The specified filename is command- and file-name expanded then tested to see if it has the specified relationship to the real user. If the file does not exist or is inaccessible, all inquiries return false (0). Command executions succeed, returning true, if the command exits with status 0; otherwise they fail, returning false. If more detailed status information is required, the command should be executed outside of an expression and the status variable examined. Control of the Flowcsh contains a number of commands that can be used to regulate the flow of control in command files (shell scripts) and (in limited but useful ways) from terminal input. These commands all operate by forcing the shell to reread or skip parts of its input and, due to the implementation, restrict the placement of some of the commands. The foreach, switch, and while statements, as well as the if-then-else form of the if statement require that the major keywords appear in a single simple command on an input line as shown below. If the shell's input is not seekable, the shell buffers input whenever a loop is being read and performs seeks in this internal buffer to accomplish the rereading implied by the loop. (To the extent that this allows, backward gotos succeed on non-seekable inputs.) Signal Handlingcsh normally ignores quit signals. Jobs running in background mode are immune to signals generated from the keyboard, including hangups. Other signals have the values which the shell inherited from its parent. csh's handling of interrupts and terminate signals in shell scripts can be controlled by onintr. Login shells catch the terminate signal; otherwise this signal is passed on to children from the state in the shell's parent. In no case are interrupts allowed when a login shell is reading the file .logout. Command Line Parsingcsh splits input lines into words at blanks and tabs. The following exceptions (parser metacharacters) are considered separate words:
The backslash (\) removes the special meaning of these parser metacharacters. A parser metacharacter preceded by a backslash is interpreted as its ASCII value. A newline character (ASCII 10) preceded by a backslash is equivalent to a blank. Strings enclosed in single or double quotes form parts of a word. Metacharacters in these strings, including blanks and tabs, do not form separate words. Within pairs of backslashes or quotes, a newline preceded by a backslash gives a true newline character. When csh's input is not a terminal, the # character introduces a comment terminated by a newline. CSH VARIABLEScsh maintains a set of variables. Each variable has a value equal to zero or more strings (words). Variables have names consisting of up to 80 letters and digits starting with a letter. The underscore character is considered a letter. The value of a variable may be displayed and changed by using the set and unset commands. Some of the variables are Boolean, that is, the shell does not care what their value is, only whether they are set or not. Some operations treat variables numerically. The at sign (@) command permits numeric calculations to be performed and the result assigned to a variable. The null string is considered to be zero, and any subsequent words of multi-word values are ignored. After the input line is aliased and parsed, and before each command is executed, variable expansion is performed keyed by the dollar sign ($) character. Variable expansion can be prevented by preceding the dollar sign with a backslash character (\) except within double quotes (") where substitution always occurs. Variables are never expanded if enclosed in single quotes. Strings quoted by single quotes are interpreted later (see Command Substitution) so variable substitution does not occur there until later, if at all. A dollar sign is passed unchanged if followed by a blank, tab, or end-of-line. Input/output redirections are recognized before variable expansion, and are variable expanded separately. Otherwise, the command name and entire argument list are expanded together. Unless enclosed in double quotes or given the :q modifier, the results of variable substitution may eventually be command and file name substituted. Within double quotes, a variable whose value consists of multiple words expands to a portion of a single word, with the words of the variable's value separated by blanks. When the :q modifier is applied to a substitution, the variable expands to multiple words with each word separated by a blank and quoted to prevent later command or file name substitution. The following metasequences are provided for introducing variable values into the shell input. Except as noted, it is an error to reference a variable that is not set.
The modifiers :h, :t, :r, :q, and :x can be applied to the substitutions above, as can :gh, :gt, and :gr. If curly braces ({ }) appear in the command form, the modifiers must appear within the braces. The current implementation allows only one : modifier on each $d expansion. The following substitutions cannot be modified with : modifiers:
Pre-Defined and Environment VariablesThe following variables have special meaning to the shell. Of these autologout, argv, cwd, home, path, prompt, shell, and status are always set by the shell. Except for cwd and status, this setting occurs only at initialization (initial execution of csh). These variables are not modified unless modified explicitly by the user. csh copies the HP-UX environment variable USER into the shell variable user, the environment variable TERM into term, the environment variable HOME into home, and PATH into path. csh copies these values back into the environment whenever the csh variables are reset. In a windowed environment, if csh detects that the window has changed size, csh sets the environment variables LINES and COLUMNS to match the new window size.
Command and File name SubstitutionThe remaining substitutions, command and file name substitution, are applied selectively to the arguments of built-in commands. This means that portions of expressions that are not evaluated are not subjected to these expansions. For commands which are not internal to the shell, the command name is substituted separately from the argument list. This occurs very late, after input-output redirection is performed, and in a child of the main shell. Command SubstitutionCommand substitution is indicated by a command enclosed in grave accents (`...`). The output from such a command is normally broken into separate words at blanks, tabs and newlines, with null words being discarded; this text then replacing the original string. Within double quotes, only newlines force new words; blanks and tabs are preserved. In any case, the single final newline does not force a new word. Note that it is thus possible for a command substitution to yield only part of a word, even if the command outputs a complete line. File name SubstitutionEach command word is processed as a pattern for file name substitution, also known as globbing, and replaced with a sorted list of file names which match the pattern. The form of the patterns is the Pattern Matching Notation defined by regexp(5) with the following exceptions:
Input/OutputThe standard input and standard output of a command can be redirected with the following syntax:
A command receives the environment in which the shell was invoked as modified by the input-output parameters and the presence of the command in a pipeline. Thus, unlike some previous shells, commands executed from a shell script have no access to the text of the commands by default; rather they receive the original standard input of the shell. The << mechanism should be used to present inline data. This permits shell scripts to function as components of pipelines and allows the shell to block-read its input. Diagnostic output can be directed through a pipe with the standard output. Simply use the form |& rather than | by itself. File Name CompletionIn typing file names as arguments to commands, it is no longer necessary to type a complete name, only a unique abbreviation is necessary. When you want the system to try to match your abbreviation, press the ESC key. The system then completes the file name for you, echoing the full name on your terminal. If the abbreviation does not match an available file name, the terminal's bell is sounded. The file name may be partially completed if the prefix matches several longer file names. In this case, the name is extended up to the ambiguous deviation, and the bell is sounded. File name completion works equally well when other directories are addressed. In addition, the tilde (~) convention for home directories is understood in this context. Viewing a File or Directory ListAt any point in typing a command, you can request "what files are available" or "what files match my current specification". Thus, when you have typed: % cd ~speech/data/bench/fritz/ you may wish to know what files or subdirectories exist (in ~speech/data/bench/fritz), without aborting the command you are typing. Typing CTRL-D at this point lists the files available. Files are listed in multicolumn format, sorted by column. Directories and executable files are identified by a trailing / and *, respectively. Once printed, the command is re-echoed for you to complete. Additionally, you may want to know which files match a prefix, the current file specification so far. If you had typed: % cd ~speech/data/bench/fr followed by a CTRL-D, all files and subdirectories whose prefix was fr in the directory ~speech/data/bench would be printed. Notice that the example before was simply a degenerate case of this with a null trailing file name. (The null string is a prefix of all strings.) Notice also that a trailing slash is required to pass to a new sub-directory for both file name completion and listing. Note that the degenerate case % ~^D prints a full list of login names on the current system. Command Name RecognitionCommand name recognition and completion works in the same manner as file name recognition and completion above. The current value of the environment variable PATH is used in searching for the command. For example % newa [Escape] might expand to % newaliases Also, % new [Control]-[D] lists all commands (along PATH) that begin with new. As an option, if the shell variable listpathnum is set, a number indicating the index in PATH is printed next to each command on a [Control]-[D] listing. AutologoutA new shell variable has been added called autologout. If the terminal remains idle (no character input) at the shell's top level for a number of minutes greater than the value assigned to autologout, you are automatically logged off. The autologout feature is temporarily disabled while a command is executing. The initial value of autologout is 600. If unset or set to 0, autologout is entirely disabled. Command Line ControlA ^R re-prints the current command line; ^W erases the last word entered on the current command line. SanityC shell restores your terminal to a sane mode if it appears to return from some command in raw, cbreak, or noecho mode. Saving Your History Buffercsh has the ability to save your history list between login sessions. If the shell variable savehist is set to a number, that number of command events from your history list is saved. For example, placing the line set history=10 savehist=10 in your .cshrc file maintains a history buffer of length 10 and saves the entire list when you logout. When you log back in, the entire buffer is restored. The commands are saved in the file .history in your login directory. EXTERNAL INFLUENCESEnvironment VariablesLC_COLLATE determines the collating sequence used in evaluating pattern matching notation for file name substitution. LC_CTYPE determines the interpretation of text as single and/or multi-byte characters, the classification of characters as letters, and the characters matched by character class expressions in pattern matching notation. LANG determines the language in which messages are displayed. If LC_COLLATE or LC_CTYPE is not specified in the environment or is set to the empty string, the value of LANG is used as a default for each unspecified or empty variable. If LANG is not specified or is set to the empty string, a default of "C" (see lang(5)) is used instead of LANG. If any internationalization variable contains an invalid setting, csh behaves as if all internationalization variables are set to "C". See environ(5). LARGESCRIPTS, when defined, enables csh to execute scripts that are larger than 1 GB. WARNINGSThe .cshrc file should be structured such that it cannot generate any output on standard output or standard error, including occasions when it is invoked without an affiliated terminal. rcp(1) causes .cshrc to be sourced, and any output generated by this file, even to standard error causes problems. Commands such as stty(1) should be placed in .login, not in .cshrc, so that their output cannot affect rcp(1). csh has certain limitations. Words or environment variables can be no longer than 10240 bytes. The system limits argument lists to 10240 bytes. The number of arguments to a command which involves file name expansion is limited to one-sixth the number of bytes allowed in an argument list. Command substitutions may substitute no more bytes than are allowed in an argument list. To detect looping, the shell restricts the number of alias substitutions on a single line to 20. When a command is restarted from a stop, csh prints the directory it started in if it is different from the current directory; this can be misleading (i.e., wrong) because the job may have changed directories internally. Shell built-in functions are not stoppable/restartable. Command sequences of the form a ; b ; c are also not handled gracefully when stopping is attempted. If you interrupt b, the shell then immediately executes c. This is especially noticeable if this expansion results from an alias. It suffices to place the sequence of commands in parentheses to force it into a subshell; i.e., ( a ; b ; c ). Because of the signal handling required by csh, interrupts are disabled just before a command is executed, and restored as the command begins execution. There may be a few seconds delay between when a command is given and when interrupts are recognized. Control over tty output after processes are started is primitive; perhaps this will inspire someone to work on a good virtual terminal interface. In a virtual terminal interface much more interesting things could be done with output control. Alias substitution is most often used to clumsily simulate shell procedures; shell procedures should be provided rather than aliases. Commands within loops, prompted for by ?, are not placed in the history list. Control structure should be parsed rather than being recognized as built-in commands. This would allow control commands to be placed anywhere, to be combined with |, and to be used with & and ; metasyntax. It should be possible to use the : modifiers on the output of command substitutions. All and more than one : modifier should be allowed on $ substitutions. Terminal type is examined only the first time you attempt recognition. To list all commands on the system along PATH, enter [Space]-[Ctrl]-[D]. The csh metasequence !~ does not work. In an international environment, character ordering is determined by the setting of LC_COLLATE, rather than by the binary ordering of character values in the machine collating sequence. This brings with it certain attendant dangers, particularly when using range expressions in file name generation patterns. For example, the command, rm [a-z]* might be expected to match all file names beginning with a lowercase alphabetic character. However, if dictionary ordering is specified by LC_COLLATE, it would also match file names beginning with an uppercase character (as well as those beginning with accented letters). Conversely, it would fail to match letters collated after z in languages such as Norwegian. The correct (and safe) way to match specific character classes in an international environment is to use a pattern of the form: rm [[:lower:]]* This uses LC_CTYPE to determine character classes and works predictably for all supported languages and codesets. For shell scripts produced on non-internationalized systems (or without consideration for the above dangers), it is recommended that they be executed in a non-NLS environment. This requires that LANG, LC_COLLATE, etc., be set to "C" or not set at all. csh implements command substitution by creating a pipe between itself and the command. If the root file system is full, the substituted command cannot write to the pipe. As a result, the shell receives no input from the command, and the result of the substitution is null. In particular, using command substitution for variable assignment under such circumstances results in the variable being silently assigned a NULL value. Relative path changes (such as cd ..), when in a symbolically linked directory, cause csh's knowledge of the working directory to be along the symbolic path instead of the physical path. Prior to HP-UX Release 9.0, csh, when getting its input from a file, would exit immediately if unable to execute a command (such as if it was unable to find the command). Beginning at Release 9.0, csh continues on and attempts to execute the remaining commands in the file. However, if the old behavior is desired for compatibility purposes, set the environment variable EXITONERR to 1. When LARGESCRIPTS is defined, the shell retains as little input as possible in memory. Thus, certain constructs like goto, that involve rewinding of the shell's input, may not work properly. Non-interactive shells will not read the ~/.history file at the beginning of execution. If required by the script, the ~/.history file needs to be read explicitly, using the source command. FILES
|
Printable version | ||
|