Sub-shell, command replacement, command combination, shell command replacement combination

Source: Internet
Author: User

Sub-shell, command replacement, command combination, shell command replacement combination

The so-called sub-shell is to create a new shell environment from the current shell environment. This new shell environment is called subshell ), the environment for enabling a sub-shell is called the parent shell of the sub-shell. The relationship between the sub-shell and the parent shell is actually the relationship between the sub-process and the parent process, except that the sub-shell and the parent shell are associated with the bash process.

The sub-shell inherits many environments from the parent shell, such as variables, command full path, file descriptor, and current working directory. However, the sub-shell has many types, different types of sub-shells inherit different environments.

Available$ BASH_SUBSHELLVariable to view the number of sub-shell layers starting from the current process,$ BASHPIDView the bash pid, which is different from the special variable "$", because "$" is inherited from the parent process.

1.1.1 when to generate a subshell

Strictly speaking, apart from directly executing bash built-in commands, all commands and scripts executed in the bash environment will generate sub-shells (meaning these commands are executed in the sub-shell environment ), to understand the sub-shell and what type of sub-shell is generated, you need to understand how to generate sub-processes in Linux.

There are three ways to create sub-processes on Linux: one is fork, the other is exec, and the other is clone. There is no need to clone the link because it is used to implement threads in Linux.

(1). fork is a replication process, which will copy copies of the current process (regardless of the mode of replication at write time) and hand over these resources to the child process in an appropriate way. Therefore, the sub-process has the same resources as the parent process, including the content in the memory, so it also includes environment variables and variables. But the Parent and Child processes are completely independent. They are two instances of a program.

(22.16.exe c is to load another application to replace the currently running process, that is, to load a new program without creating a new process. Exec has another action: After the process is executed, exit the shell environment where exec is located. To ensure process security,To form a new and independent sub-process, the current process is fork first, and then exec is called on the Sub-process generated by fork to load the new program to replace the sub-process.. For example, if you execute the cp command in bash, A bash will be generated by fork first, and then the exec loads the cp program to overwrite the sub-bash process into the cp process.

Next we will explain the sub-shell problem. Generally, the content of the fork child process is the same as that of the parent process, including variables. For example, the variables of the parent process can also be obtained when the cp command is executed. But where is the cp Command executed? In the sub-shell. Run the cp command and press Enter. The current bash process fork generates a subbash, and then the subbash loads the cp program through exec to replace the subbash.

Can it be understood that all commands and scripts run in the sub-shell environment? Obviously, the built-in bash commands mentioned above are not run in the sub-shell. All other methods are completed in the sub-shell, but the methods are different.

There are several situations:

  • ①.Execute bash built-in commands: Bash built-in commands are very special. The parent process does not create sub-processes to execute these commands, but directly runs them in the current bash process. If the built-in command is placed in the pipeline, the built-in command will belong to the same process group as the process on the left of the pipeline. Therefore, the sub-process will still be created, but not necessarily the sub-shell. Please read the following information before proceeding.
  • ②.Execute bash command itself: This is a coincidence. Bash commands are built-in bash commands. Executing the built-in commands in the Current shell environment will not create subshells, that is, there will be no independent bash processes, the actual result is displayed as a new bash sub-process. One of the reasons is that executing the bash command loads various environment configuration items, so that the parent bash environment is protected without being overwritten, so it should exist as a sub-shell. Although the content of the bash sub-process from fork completely inherits the parent shell,However, because the environment configuration item is re-loaded, the sub-shell does not inherit normal variables. More accurately, it overwrites the variables inherited from the parent shell.Try to define a variable in the/etc/bashrc file, and then execute the environment variable with the same export name but different values in the parent shell to check the value of the variable in the sub-shell?
    • In fact, execute the bash command, that is, it can be considered to have entered the sub-shell, or it can be considered not to have entered the sub-shell. From the perspective that bash is a built-in command, it will not enter the sub-shell, which can be verified from the value of $ BASH_SUBSHELL after the bash command is executed. However, after executing the bash command, it enters the new shell environment and has its parent bash process. Therefore, it enters the subshell.
  • ③.Execute shell scripts: Because the first line in the script is always "#! /Bin/bash "or" bash xyz. sh "directly, this is the same as executing bash to enter the sub-shell. It is to use the bash command to enter the sub-shell. However, the bash command at this time is different from the options implied by directly executing the bash command in scenario 2, so the inherited and loaded shell environments are different. This is also true,It only inherits some environment variables of the parent shell, and all other environments are initialized.
    • In addition, the execution of the shell script has an action: the sub-shell is automatically exited after the command is executed.
  • ④.Execute non-bash built-in commandsFor example, execute the cp command and grep command. They directly fork a bash process and then use the exec loader to replace the sub-bash. This type of child process inherits all the parent bash environments. But strictly speaking, this is not a sub-shell, because the exec-loaded program has replaced the sub-bash process, which means that many bash environments are lost.
  • ⑤.Replacement of commands without built-in commands: When the command line contains the command replacement part, a sub-shell is enabled to execute this part first, and then the execution result is returned to the current command. Because this subshell is not a subshell that is entered through the bash command, it inherits all the variable content of the parent shell. This explains that the result of "$" in "echo $ (echo $)" is the pid of the current bash, rather than the pid of the sub-shell, however, "echo $ (echo $ BASHPID)" is different from the pid of the parent bash process because it is not a sub-shell that uses bash commands.
  • 6.Use parentheses () to combine a series of commandsFor example (ls; date; echo haha), an independent sub-shell is opened to execute the commands in the brackets. This is equivalent to scenario 5.

Note that,The environment settings of the sub-shell are not stuck to the parent shell environment, that is, the variables of the sub-shell will not affect the parent shell.

In fact, how to determine whether the Sub-shell is entered is very simple. Execute "echo $ BASHPID". If the value is different from the pid value of the parent bash process, it indicates that the sub-shell is entered.

For example:

[Root @ xuexi ~] # Echo $ BASHPID # pid12904 of the current bash process [root @ xuexi ~] # Echo haha | echo $ BASHPID # A sub-process group enabled by a non-built-in command enters the sub-shell13412 [root @ xuexi ~] # (Echo $ BASHPID) # use parentheses to enter the sub-shell13413 [root @ xuexi ~] # Echo $ (echo $ BASHPID) # Replace $ () with the command to enter the sub-shell13433
1.1.2 command replacement and command combination

In Linux, use quotation marks ('') or $ () to execute command replacement. Use parentheses () to combine a series of commands.

[Root @ xuexi ~] # Echo what date it is? $ (Date + % F) what date it is? 2016-09-25 [root @ xuexi tmp] # echo what date it is? 'Date + % F' # Or use backquotes

You can run the $ () command in parentheses in advance of the entire command, and insert the execution result to the command replacement symbol. Because the results of command replacement are often handed over to external commands, there should be no line breaks in the results, by default, all linefeeds are replaced with spaces (in fact, all blank spaces are compressed into a single space ).

For example:

[root@xuexi ~]# echo -e "a\nb"ab
[root@xuexi ~]# echo `echo -e "a\nb\t   \tc"`a b c

You can use double quotation marks to retain white spaces.

[root@xuexi ~]# echo "`echo -e "a\nb\t   \tc"`"ab               c

You can see from the above,There are two steps to replace a command: (1) enable the sub-shell to execute the command (2) package the output result of the sub-shell and insert it into the command line. However, the process of packaging output results is controllable (for example, double quotation marks are used above ).

Most of the time, you need to use "cat a.txt | command" or run $ (cat a.txt) to pass the contents in file a.txt, but this is not the best method. They are equivalent to "<a.txt" and "$ (<a.txt )".

If you use parentheses to enclose a series of commands, these commands can be run independently of the current bash environment. This is actually a command group.

For example:

[root@xuexi ~]# (umask 077;touch new.txt;ls -l new.txt)-rw------- 1 root root 0 Aug 13 22:46 new.txt

Back to series article outline: http://www.cnblogs.com/f-ck-need-u/p/7048359.html

Reprinted please indicate the source: Success!

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.