📄 bashref.texi
字号:
as a unit. When commands are grouped, redirections may be appliedto the entire command list. For example, the output of all thecommands in the list may be redirected to a single stream.@table @code@item ()@example( @var{list} )@end examplePlacing a list of commands between parentheses causes a subshellenvironment to be created (@pxref{Command Execution Environment}), and eachof the commands in @var{list} to be executed in that subshell. Since the@var{list} is executed in a subshell, variable assignments do not remain ineffect after the subshell completes. @item @{@}@rwindex @{@rwindex @}@example@{ @var{list}; @}@end examplePlacing a list of commands between curly braces causes the list tobe executed in the current shell context. No subshell is created.The semicolon (or newline) following @var{list} is required.@end tableIn addition to the creation of a subshell, there is a subtle differencebetween these two constructs due to historical reasons. The bracesare @code{reserved words}, so they must be separated from the @var{list}by @code{blank}s or other shell metacharacters.The parentheses are @code{operators}, and arerecognized as separate tokens by the shell even if they are not separatedfrom the @var{list} by whitespace.The exit status of both of these constructs is the exit status of@var{list}.@node Coprocesses@subsection Coprocesses@cindex coprocessA @code{coprocess} is a shell command preceded by the @code{coproc}reserved word.A coprocess is executed asynchronously in a subshell, as if the commandhad been terminated with the @samp{&} control operator, with a two-way pipeestablished between the executing shell and the coprocess.The format for a coprocess is:@example@code{coproc} [@var{NAME}] @var{command} [@var{redirections}]@end example@noindentThis creates a coprocess named @var{NAME}.If @var{NAME} is not supplied, the default name is @var{COPROC}.@var{NAME} must not be supplied if @var{command} is a simplecommand (@pxref{Simple Commands}); otherwise, it is interpreted asthe first word of the simple command.When the coproc is executed, the shell creates an array variable(@pxref{Arrays})named @var{NAME} in the context of the executing shell.The standard output of @var{command}is connected via a pipe to a file descriptor in the executing shell,and that file descriptor is assigned to @var{NAME}[0].The standard input of @var{command}is connected via a pipe to a file descriptor in the executing shell,and that file descriptor is assigned to @var{NAME}[1].This pipe is established before any redirections specified by thecommand (@pxref{Redirections}).The file descriptors can be utilized as arguments to shell commandsand redirections using standard word expansions.The process ID of the shell spawned to execute the coprocess isavailable as the value of the variable @var{NAME}_PID.The @code{wait}builtin command may be used to wait for the coprocess to terminate.The return status of a coprocess is the exit status of @var{command}.@node GNU Parallel@subsection GNU ParallelGNU Parallel, as its name suggests, can be used to build and run commandsin parallel. You may run the same command with different arguments, whetherthey are filenames, usernames, hostnames, or lines read from files.For a complete description, refer to the GNU Parallel documentation. A fewexamples should provide a brief introduction to its use.For example, it is easy to prefix each line in a text file with a specifiedstring:@examplecat file | parallel -k echo prefix_string@end example@noindentThe @option{-k} option is required to preserve the lines' order.Similarly, you can append a specified string to each line in a text file:@examplecat file | parallel -k echo @{@} append_string@end exampleYou can use Parallel to move files from the current directory when thenumber of files is too large to process with one @code{mv} invocation:@examplels | parallel mv @{@} destdir@end exampleAs you can see, the @{@} is replaced with each line read from standard input.This will run as many @code{mv} commands as there are files in the currentdirectory. You can emulate a parallel @code{xargs} by adding the @option{-X}option:@examplels | parallel -X mv @{@} destdir@end exampleGNU Parallel can replace certain common idioms that operate on lines readfrom a file (in this case, filenames):@example for x in $(cat list); do do-something1 $x config-$x do-something2 < $x done | process-output@end example@noindentwith a more compact syntax reminiscent of lambdas:@examplecat list | parallel "do-something1 @{@} config-@{@} ; do-something2 < @{@}" | process-output@end exampleParallel provides a built-in mechanism to remove filename extensions, whichlends itself to batch file transformations or renaming:@examplels *.gz | parallel -j+0 "zcat @{@} | bzip2 >@{.@}.bz2 && rm @{@}"@end example@noindentThis will recompress all files in the current directory with names endingin .gz using bzip2, running one job per CPU (-j+0) in parallel.If a command generates output, you may want to preserve the input order inthe output. For instance, the following command@example@{ echo foss.org.my ; echo debian.org; echo freenetproject.org; @} | parallel traceroute@end example@noindentwill display as output the traceroute invocation that finishes first. Usingthe @option{-k} option, as we saw above@example@{ echo foss.org.my ; echo debian.org; echo freenetproject.org; @} | parallel -k traceroute@end example@noindentwill ensure that the output of @code{traceroute foss.org.my} is displayed first.@node Shell Functions@section Shell Functions@cindex shell function@cindex functions, shellShell functions are a way to group commands for later executionusing a single name for the group. They are executed just likea "regular" command.When the name of a shell function is used as a simple command name,the list of commands associated with that function name is executed.Shell functions are executed in the currentshell context; no new process is created to interpret them.Functions are declared using this syntax:@rwindex function@example@var{name} () @var{compound-command} [ @var{redirections} ]@*or@*@code{function} @var{name} [()] @var{compound-command} [ @var{redirections} ]@end exampleThis defines a shell function named @var{name}. The reservedword @code{function} is optional.If the @code{function} reservedword is supplied, the parentheses are optional.The @var{body} of the function is the compound command@var{compound-command} (@pxref{Compound Commands}).That command is usually a @var{list} enclosed between @{ and @}, butmay be any compound command listed above.@var{compound-command} is executed whenever @var{name} is specified as thename of a command.Any redirections (@pxref{Redirections}) associated with the shell functionare performed when the function is executed.A function definition may be deleted using the @option{-f} option to the@code{unset} builtin (@pxref{Bourne Shell Builtins}).The exit status of a function definition is zero unless a syntax erroroccurs or a readonly function with the same name already exists.When executed, the exit status of a function is the exit status of thelast command executed in the body.Note that for historical reasons, in the most common usage the curly bracesthat surround the body of the function must be separated from the body by@code{blank}s or newlines.This is because the braces are reserved words and are only recognizedas such when they are separated from the command listby whitespace or another shell metacharacter.Also, when using the braces, the @var{list} must be terminated by a semicolon,a @samp{&}, or a newline.When a function is executed, the arguments to thefunction become the positional parametersduring its execution (@pxref{Positional Parameters}).The special parameter @samp{#} that expands to the number ofpositional parameters is updated to reflect the change.Special parameter @code{0} is unchanged.The first element of the @env{FUNCNAME} variable is set to thename of the function while the function is executing.All other aspects of the shell executionenvironment are identical between a function and its callerwith these exceptions:the @env{DEBUG} and @env{RETURN} trapsare not inherited unless the function has been given the@code{trace} attribute using the @code{declare} builtin orthe @code{-o functrace} option has been enabled withthe @code{set} builtin,(in which case all functions inherit the @env{DEBUG} and @env{RETURN} traps),and the @env{ERR} trap is not inherited unless the @code{-o errtrace}shell option has been enabled.@xref{Bourne Shell Builtins}, for the description of the@code{trap} builtin.The @env{FUNCNEST} variable, if set to a numeric value greaterthan 0, defines a maximum function nesting level. Functioninvocations that exceed the limit cause the entire command toabort.If the builtin command @code{return}is executed in a function, the function completes andexecution resumes with the next command after the functioncall.Any command associated with the @code{RETURN} trap is executedbefore execution resumes.When a function completes, the values of thepositional parameters and the special parameter @samp{#}are restored to the values they had prior to the function'sexecution. If a numeric argument is given to @code{return},that is the function's return status; otherwise the function'sreturn status is the exit status of the last command executedbefore the @code{return}.Variables local to the function may be declared with the@code{local} builtin. These variables are visible only tothe function and the commands it invokes.Function names and definitions may be listed with the@option{-f} option to the @code{declare} or @code{typeset}builtin commands (@pxref{Bash Builtins}).The @option{-F} option to @code{declare} or @code{typeset}will list the function names only(and optionally the source file and line number, if the @code{extdebug}shell option is enabled).Functions may be exported so that subshellsautomatically have them defined with the@option{-f} option to the @code{export} builtin(@pxref{Bourne Shell Builtins}).Note that shell functions and variables with the same name may resultin multiple identically-named entries in the environment passed to theshell's children.Care should be taken in cases where this may cause a problem.Functions may be recursive.The @code{FUNCNEST} variable may be used to limit the depth of thefunction call stack and restrict the number of function invocations.By default, no limit is placed on the number of recursive calls.@node Shell Parameters@section Shell Parameters@cindex parameters@cindex variable, shell@cindex shell variable@menu* Positional Parameters:: The shell's command-line arguments.* Special Parameters:: Parameters denoted by special characters.@end menuA @var{parameter} is an entity that stores values.It can be a @code{name}, a number, or one of the special characterslisted below.A @var{variable} is a parameter denoted by a @code{name}.A variable has a @var{value} and zero or more @var{attributes}.Attributes are assigned using the @code{declare} builtin command(see the description of the @code{declare} builtin in @ref{Bash Builtins}).A parameter is set if it has been assigned a value. The null string isa valid value. Once a variable is set, it may be unset only by usingthe @code{unset} builtin command.A variable may be assigned to by a statement of the form@example@var{name}=[@var{value}]@end example@noindentIf @var{value}is not given, the variable is assigned the null string. All@var{value}s undergo tilde expansion, parameter and variable expansion,command substitution, arithmetic expansion, and quoteremoval (detailed below). If the variable has its @code{integer}attribute set, then @var{value} is evaluated as an arithmetic expression even if the @code{$((@dots{}))}expansion is not used (@pxref{Arithmetic Expansion}).Word splitting is not performed, with the exceptionof @code{"$@@"} as explained below.Filename expansion is not performed.Assignment statements may also appear as arguments to the@code{alias}, @code{declare}, @code{typeset}, @code{export}, @code{readonly},and @code{local} builtin commands.In the context where an assignment statement is assigning a value to a shell variable or array index (@pxref{Arrays}), the @samp{+=}operator can be used to append to or add to the variable's previous value.When @samp{+=} is applied to a variable for which the @var{integer} attributehas been set, @var{value} is evaluated as an arithmetic expression andadded to the variable's current value, which is also evaluated.When @samp{+=} is applied to an array variable using compound assignment(@pxref{Arrays}), thevariable's value is not unset (as it is when using @samp{=}), and newvalues are appended to the array beginning at one greater than the array'smaximum index (for indexed arrays), or added as additional key-value pairsin an associative array.When applied to a string-valued variable, @var{value} is expanded andappended to the variable's value.@node Positional Parameters@subsection Positional Parameters@cindex parameters, positionalA @var{positional parameter} is a parameter denoted by one or moredigits, other than the single digit @code{0}. Positional parameters areassigned from the shell's arguments when it is invoked,and may be reassigned using the @code{set} builtin command.Positional parameter @code{N} may be referenced as @code{$@{N@}}, oras @code{$N} when @code{N} consists of a single digit.Positional parameters may not be assigned to with assignment statements.The @code{set} and @code{shift} builtins are used to set andunset them (@pxref{Shell Builtin Commands}).The positional parameters aretemporarily replaced when a shell function is executed(@pxref{Shell Functions}).When a positional parameter consisting of more than a singledigit is expanded, it must be enclosed in braces.
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -