Basic analysis of Linux operating system (vii)--bash (Shell) Basics (5)

Source: Internet
Author: User
Tags arithmetic locale posix


Xi. functions
The shell function is defined by the description of the shell grammar above and holds a series of commands waiting to be executed later. When the shell function name is used as a simple command name, a series of commands associated with the function name are executed. Functions are executed in the context of the current shell, and no new processes are created to interpret them (this contrasts with the execution of the shell script). When the function is executed, the parameters of the function become positional parameters during execution. Special parameter # is updated to reflect this change. Special parameter 0 does not change. When a function executes, the first element of the funcname variable is set to the name of the function.
All other aspects of the shell execution environment are identical between the function and its callers, except in the following cases: the Debug trap and the return trap (see the description of the built-in command grabber for Shell BUILTIN commands below) are non-inheritable, Unless the function has been set to the Trace property (see the relevant description of the built-in command declare below) or the shell's built-in command set's-o functrace option is enabled (in this case, the function inherits the debug and return traps), The Err grabber is also non-inherited unless the-O errtrace option is enabled.
Local variables in the function can be declared using the built-in command local. Typically, variables and their values are shared between the function and its callers.
Variable funcnest, if set to a value greater than 0, defines the maximum nesting level of the function. A function call that exceeds this limit causes all commands to be canceled.
If the built-in command is executed in the return function, the function execution ends and the execution begins again with the next command after the function call. Any command associated with the return trap will be executed before the function is re-executed. When a function executes, the value of the position variable and the special variable # is restored to the value before the function executes.
function names and definitions can be listed using the built-in command declare or typeset plus the-f parameter. If you use the-f option in the Declare or typeset command, only the function name is listed (if the Shell's extdebug option is turned on, there are source files and line numbers). Functions can be exported with the built-in command export plus the-f parameter so that they are automatically defined in the child shell. Function definitions can also be unset with built-in commands and removed using the-f option. Note that the same Shell function and variable name may result in multiple entries with the same name when the environment variable is passed to the child shell.
The function can be recursive. Variable funcnest can be used to limit the depth of the function call stack and limit the number of function calls. By default, there is no hard limit for the number of recursive calls.

12. Arithmetic operations
In a certain environment, the shell allows arithmetic expressions to be numerically computed (see built-in command let and declare and arithmetic expressions). The evaluation is done using a fixed-width integer with no overflow check, but dividing by 0 is still restricted and is marked with an error. The operators and their precedence and aggregation levels are the same as in the C language. The list of the following operators is grouped by operand equivalence precedence. The order of precedence is decremented.
id++ id--variable after self-increment and post-decrement (self-increment-decrement after assignment)
++id--id variable first self-increment and first self-decrement (self-increment-decrement before assignment)
-+ (Single purpose) take negative/take positive
! ~ Logical AND bitwise inverse
* * exponentiation
*/% multiply, except, modulo operation (take surplus)
+-Add, subtract
<< >> Left/Right displacement
<= >= < > Comparison
= = = Equal/unequal
& Bit with (and)
^ Bit XOR (exclusive OR)
| Bit or (or)
&& logic and (and)
|| Logical OR (OR)
expr?expr:expr condition operation
= *=/=%= + = = <<= >>= &= ^= |= Assignment
EXPR1, expr2 comma-expression
Shell variables are allowed as operands, and parameter expansion occurs before an expression evaluates. In an expression, you can refer to a shell variable by name, without using the syntax for the parameter expansion, at which point the shell variable is empty or the value of the cancel calculation is set to 0. The value of a variable is when the variable is referenced as an arithmetic expression or when the variable is given an integer property value using the Declare-i option. evaluates the variable. The null value is calculated as the limit. When you use a shell variable in an expression, you do not have to enable integer properties.
Constants with a leading 0 are treated as octal numbers, and a leading representation of 0x or 0X is hexadecimal. Otherwise, the number will take the form: [Base#]n, where base is an optional radix, is a decimal number between 2 and 64 representing the arithmetic cardinality, n is the number in this cardinality. If base# is omitted, 10 is the base. Numbers greater than 9 are followed by lowercase letters, uppercase letters, and @ and _. If base is less than or equal to 36, lowercase letters and uppercase letters can be used interchangeably when representing numbers between 10 and 35.
Operands are evaluated in order of precedence. Sub-expressions in parentheses are evaluated first and may go beyond the precedence rules above.

13. Conditional expressions
The conditional expression is used for [[Composite command and built-in command test and [, for testing file properties, for string and arithmetic comparisons. The expression consists of a single or binocular operator with the following single-or two-eye. If any of the file parameters of an operation are in the form of/dev/fd/n, then the officer Descriptor N. If the file parameter of an operation is one of/dev/stdin,/dev/stdout or/dev/stderr, the document descriptor 0,1 and 2 are examined separately.
Unless otherwise noted, the primary action on a file is to follow the symbolic link, and not the link itself, but on the target of the link.
The,< and > operators are sorted using the current locale in the order in which they are compiled when using [[]. The test command uses the ASCII encoding order.
-A file
True if file exists.
-B File
True if file exists and is a block device.
-C file
True if file exists and is a character device.
-D File
True if file exists and is a directory.
-E File
True if file exists.
-F File
True if file exists and is normal.
-G file
True if file exists and is set to the group ID (sgid).
-H file
True if file exists and is a symbolic link.
-K File
True if file exists and the ' sticky ' bit (sticky bit) is set.
-P File
True if file exists and is a named pipe (FIFO).
-R File
True if file exists and is readable.
-S file
True if file exists and the size is greater than zero.
-T FD
True if the file descriptor FD is open and corresponds to a terminal.
-U file
True if file exists and the user ID is set (suid).
-W File
True if file exists and is writable.
-X File
True if file exists and is executable.
-O File
True if file exists and is owned by a valid user ID.
-G file
True if file exists and is owned by the valid group ID.
-L File
True if file exists and is a symbolic link.
-S file
True if file exists and is a socket.
-N File
True if file exists and has been modified since it was last read.
File1-nt File2
True if the file1 is newer than file2 (based on the modified date), or if the file1 exists and file2 does not exist.
File1-ot File2
True if the file1 is older than file2, or if the file1 does not exist and the file2 exists.
File1-ef File2
True if File1 and File2 refer to the same device and inode number.
-O optname
True if the shell option optname is enabled. See the list of options in the description of the-o option under the built-in command set.
-Z String
True if string has a length of 0
-N String
True if the length of the string is not 0.
string1 = = string2
string1 = string2
True if the strings are equal. = can be used with the test command to be compatible with POSIX specifications.
String1! = string2
True if the strings are not equal.
String1 < string2
True if string1 is before string2 in the dictionary order of the current locale.
String1 > string2
True if string1 is ranked in the dictionary order of the current locale after string2.
Arg1 OP arg2
OP is one of the-eq,-ne,-lt,-le,-gt, or-ge. These arithmetic two-mesh operators, if arg1 and arg2 are equal, unequal, less than, less than or equal to, greater than, greater than or equal to the relationship, the return value is true. Arg1 and arg2 can be positive integers or negative integers.

14. Simple Command expansion
When a simple command is executed, the shell performs the following expansion, assignment, and redirection from left to right.
1. The parser is marked with a variable assignment (before the command name) and the redirection about the word is saved waiting to be processed later.
2. Characters that are not variable-assigned or redirected are expanded. If the word persists after expansion, the first word is used as the command name and the remaining word is the argument.
3. Redirects follow the rules for redirection.
4. The text after "=" in each variable assignment is preceded by a wavy line expansion, parameter expansion, command substitution, arithmetic expansion, and reference removal.
If the command name is not given, the variable assignment affects the current shell environment. Otherwise, the variable is added to the environment of the command being executed, without affecting the current shell environment. Any attempt to assign a value to a read-only variable results in an error, and the command exits with a non-0 status value.
If you do not get the command name, redirection still occurs, but it does not affect the current shell environment. A redirect error causes the command to exit with a non-0 status value.
If the command name remains after the expansion, the execution is as follows. Otherwise, the command exits. If you include command substitution in any expansion, the exit status of the entire command is the exit state that was replaced by the last command executed. If no command substitution is made, the command exits with state 0.

Xv. Execution of Orders
After the command is split into words, if the result is a simple command and an optional parameter list, the following action is performed.
If the command name does not include a slash, the shell tries to locate the command location. If there is a shell function with the same name, the function will be executed. If the name is not a function, the shell looks for it from the built-in command. If a corresponding command is found, it will be executed.
If the name is neither a shell function nor a built-in command, and there is no slash, bash looks for each element of the path variable and finds the directory that contains the executable file by name. Bash uses a hash list (hash table) to store the full pathname of the executable file. The element directory saved in the path variable is fully searched only if the command is not found in the hash table. If the lookup is unsuccessful, the shell looks for a shell function named Command_not_fount_handle that has already been defined. If the function exists, it will be executed using the source command and the parameters of the source command as arguments, and the exit status of this function will be the shell's exit state. If the function is undefined, the shell outputs an error message, returning the exit status value of 127.
If the lookup succeeds, or if the command contains one or more slashes, the shell uses a separate execution environment to execute the program. Parameter 0 is set to the given name, and the other parameters of the command are set to the given parameters, if any.
If execution fails because the file is not an executable format, and the file is not a directory, it is assumed to be a shell script, a file containing shell commands. A child shell is started to execute it. The child shell re-initializes itself as if it were invoking a new shell to process the script, but the command location cached by the parent shell is still preserved by the shell.
If the program is "#!" Begins with the file, the remainder of the first line specifies the interpreter for the program. The shell executes the specified interpreter on an operating system that does not handle this executable file format on its own. If so, the parameters of the interpreter can be composed of the following three parts:
An optional parameter, the name of the program, and a command-line argument immediately following the interpreter name in the first line of the program.

16. Command execution Environment
The shell has a concept of execution environment, which consists of the following elements:
The open file is inherited when the shell is started and modified by the redirection provided by the built-in command exec.
The current working directory is set using the CD, pushd, or POPD commands, or is inherited by the shell at startup.
The file creation pattern mask is set by using the Umask command or inherited from the shell's parent process.
Current capture, set with trap.
The shell parameters are set using variable assignments or the set command, or inherited from the parent process's environment.
A shell function that is defined during execution or inherited from the environment of the parent process.
Options are activated when invoked (either by default or by command-line arguments) or set with the SET command.
Activate the option with shopt.
The shell alias defined with alias.
Various PIDs, the process number that contains the background job, the value of $$, and the value of $ppid.
When a simple command that is not a shell function or a built-in command executes, it is started in a separate execution environment that consists of the following content. Unless otherwise noted, the values are inherited from the shell.
The shell opens the file, plus the files that are modified and added to the command using redirection.
Current working directory.
The file creation pattern mask.
Shell variables and functions that are marked for export, and the variables that are exported to the environment for this command.
The shell-captured catcher is reset to the value inherited from the shell's parent process, and the catcher ignored by the shell is ignored.
Commands that are launched in a separate environment do not affect the execution environment of the shell.
Command substitution, commands that are grouped by parentheses, and asynchronous commands are executed in a child shell environment that is copied from the shell environment, unless the shell captures the trap s that are reset to the value that the shell initiates from its parent shell. Built-in commands that are executed as part of the pipeline are also executed in a child shell environment. Modifications to the child shell environment do not affect the execution environment of the original shell.
The child shell generates a value that executes the command to replace the-e option of the inherited parent shell. If it is not POSIX mode, bash clears the-e option in such a child shell.
If the command is followed by & and job control is not enabled, the default standard input for the command will be the empty file/dev/null. Otherwise, the executed command inherits the file descriptor of the so-called Shell that is being redirected for modification.

17. Environment
When a program is called, it is given an array of strings called environments. It is a list of name-value pairs, in the form of Name=value.
The shell provides a variety of ways to operate the environment. At startup, the shell scans its environment, creates a parameter for each name found, and automatically marks it for export to the child process. The executed commands inherit the environment. The export and Declare-x commands allow parameters and functions to be added to or removed from the environment. If the value of the parameter in the environment is modified, the new value replaces the old value as part of the environment. The environment in which any executed command inherits includes the shell's initial environment, whose values may have been modified in the shell, subtracted by the unset command, plus portions added through the export and Declare-x commands.
You can temporarily enhance the environment of any simple command or function by setting the prefix as a parameter assignment. These assignment statements take effect in the environment in which this command is manufactured.
If you set the-K option with the built-in command set, all variable assignments will be replaced in the context of the command, not just those in front of the command name.
When bash executes an external command, the variable "_" is set to the full file name of the command, which is then passed to the command in that environment.

18. Exit Status
The exit state of an executed command is through the WAITPID system call or the return value of the corresponding function. The exit status is between 0 and 255, but it is necessary to explain that the shell might use a value before 125. The shell's built-in command and the exit status of the compound command are also limited to this range. In some cases, the shell uses special values to prompt for special error patterns.
From the shell's point of view, using the exit status is the command to exit with zero, which means successful execution. The exit status is 0 indicating success. A non-0 status value indicates failure. When the command receives the fatal signal N and ends, Bash uses 128+n as its exit state.
If no command is found, the child process created to execute it returns a status of 127. If a command is found but the file is not executable, the return status is 126.
If the command fails because of an error while expanding or redirecting, the exit state is greater than 0.
The shell built-in command returns a non-0 (false) state if an error occurs while executing, if the 0 (true) state is successfully returned. All built-in commands return a 2 exit state to indicate incorrect usage.
Bash itself returns the exit state of the last command executed, unless a syntax error occurs, which returns a value other than 0.
19. Signal
If bash is interactive and does not have any traps, it ignores sigterm (so that kill 0 does not end the interactive shell), SIGINT is captured and processed (so that the built-in command wait can be interrupted). In all cases, Bash ignores sigquit. If job control is functioning, Bash ignores sigttin, Sigttou, and SIGTSTP.
Non-built-in commands that are run through bash have signal processors that inherit the corresponding values from their parent shell. When the job controller fails, asynchronous commands ignore SIGINT and sigquit, in addition to these inherited processors. Commands that run with the result of a command override ignore the job control signals generated by the keyboard Sigttin,sigttou and SIGTSTP.
By default, the shell exits when a sighup signal is received. Before exiting, the interactive shell re-sends the signal sighup to all jobs, whether they are running or stopped. Jobs that have been stopped send sigcont signals to ensure they receive the sighup signal. To prevent the shell from sending a signal to a separate job, you should use the built-in command disown to remove it from the job table or use Disown-h to mark it as not receiving sighup.
If the Huponexit option is set with the shopt command, Bash sends a sighup signal to all jobs when the interactive logon shell exits.
If bash is waiting for the command to finish and receives a signal that sets the trap, the trap will not execute until the command ends. When bash waits for an asynchronous command with a built-in command wait, it has been set to receive the capture signal, which causes the built-in command wait to be returned immediately with a status value greater than 128. The trap is then executed immediately.

20. Operation Control
Job control refers to the ability to choose to stop (or suspend) the execution of a process, and then continue (or resume) the execution of the process afterwards. This functionality is typically provided by the user through an interactive interface by the operating system kernel Terminal driver and bash.
The shell associates each pipe to a job. It holds a job table that is currently executing that can be listed with the jobs command. When bash starts a job asynchronously (in the background), it outputs such a line:
[1] 25647
This indicates that the job number is 1, and the process ID of the last process in the pipeline associated with the job is 25647. All processes in a single pipeline are members of the same job. Bash uses the job concept as the basis for job control.
In order to simplify the implementation of the user interface for job control, the operating system maintains a "current terminal process Group identification" concept. The members of this process group (process group ID equals the process of the current terminal process group ID) can receive signals generated by the keyboard, such as SIGINT. These processes are referred to as foreground processes. The process behind the scenes is a process in which the process group ID differs from the terminal, and these processes are not affected by the signal generated by the keyboard. Only the foreground process can read from the terminal or write to the terminal. When a background process attempts to read/write a terminal, it receives a sigttin (Sigttou) signal sent by the kernel terminal driver. If this signal is not captured, the process will be suspended.
If there is a bash running operating system that supports job control, bash will include the facilities that use it. Typing the suspend pending character (usually ^z, control-z) while a process is running will cause the process to stop and return control to bash. Entering the delayed suspend character (usually ^y,control-y) will cause the process to stop when it tries to read input from the terminal and return control to bash. The user can then control the state of the job, use the BG command to keep it running in the background, the FG command to keep it running in the foreground, or the kill command to kill it. ^z takes effect immediately, and there are other aspects of the effect that are discarded while waiting for the output and before typing the character.
There are many ways to refer to jobs in the shell. The character% can introduce the job name. Jobs with number n can be referred to in the form of%n. A job can also be referred to by a prefix that starts its name, or a substring in the command line. For example,%CE refers to a suspended CE job. If the prefix matches more than one job, bash errors. On the other hand, using%?ce, you can refer to any job that contains the string CE on any command line. If the substring matches more than one job, bash errors. The symbol percent and%+ refer to the concept of the shell's current job, the last job that the foreground is paused in, or the job that is started in the background. The previous job can be referred to using%-. In the output information about the job (for example, the output of the jobs command), the current job is always marked as +, and the previous job is marked as-.
Simply name a job to put it to the foreground:%1 is synonymous with "FG%1", and job 1 is placed in the foreground from the background. Similarly, "%1 &" resumes Job 1 in the background and is equivalent to "BG%1".
When a job changes state, the shell immediately learns. Typically, bash waits for a prompt to be output to report a change in the job's state, thus not interrupting other output. If the built-in command set has the-B option enabled, Bash will report these changes immediately. The capture of any SIGCHLD signal executes when each child process exits.
If you try to exit Bash,shell when the job is stopped (or if the checkjobs option is turned on and running using the built-in command shopt), a warning message is displayed, and the list job and their status appear when the Checkjobs option is turned on. The jobs command can be used to detect the status of these jobs. If you try to quit again without an intermediate command, the shell does not display additional warning messages, and all stopped jobs are terminated.

21. Prompt character
During interactive execution, bash displays the main prompt PS1 when it is ready to read a command, and when it needs more input for the completion of the command, a secondary command prompt is displayed ps2,bash allows you to customize these prompt strings by entering some special characters that use backslashes to escape, as shown here:
\a
An ASCII bell character (07)
\d
Date in the form "Day of the Week" (for example, "Tue May 26")
\d{format}
Format is passed to Strftime (3), the result is inserted into the hint string, and the empty format uses the locale-specific time format. Curly braces are required
\e
An ASCII escape character (033)
\h
Host name, first "." The previous section
\h
The full host name
\j
The number of jobs currently managed by the Shell
\l
The basic part of the Shell's device name
\ n
Line break
\ r
Enter
\s
The name of the shell, the base-name part of
\ t
Current time, HH:MM:SS format with 24-hour system
\ t
Current time, HH:MM:SS format with 12-hour system
\@
Current time, using 12-hour morning/afternoon (AM/PM) format
\a
Current time, using 24-hour morning/afternoon format
\u
User name of the current user
\v
Version of Bash
\v
Bash release number, version number plus patch level
\w
Current working directory
\w
Basic parts of the current working directory
\!
The history number of this command
\#
Command number for this command
\$
If the valid UID is 0, that is #, the other case is $
\nnn
Character corresponding to octal number nnn
\\
A back slash
\[
The beginning of a non-printable sequence of characters that can be used to embed the terminal control sequence at the prompt
\]
End of a non-printable character sequence
The command number and history number are usually different: The history number is the position of the command in the History list, which can contain commands recovered from the history file, and the command number is the ordinal of the command executed in the current shell session. After the string is decoded, it is expanded, expanded by parameter expansion, command substitution, arithmetic expansion, and reference removal, and finally through the shell option Promptvars processing.

This article is from the "home of the Ops" blog, so be sure to keep this source http://zhaotianyu.blog.51cto.com/132212/1793742

Basic analysis of Linux operating system (vii)--bash (Shell) Basics (5)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.