Let's start by looking at the variables.
[Email protected] ~]# dhh=1
[Email protected] ~]# echo $DHH
1
Open a child shell test
[Email protected] ~]# bash
[Email protected] ~]# echo $DHH
No value
Using the Export method
[[Email protected] ~]# exit----------Exit child shell
Exit
[Email protected] ~]# export DHH
[[email protected] ~]# bash-----------new child shell
[Email protected] ~]# echo $DHH
1
So we can say: Export can pass the variables defined by this shell to the child shell
But can the variables of the child shell be passed to the parent shell through the Exprot variable value??
[Email protected] ~]# bash
[Email protected] ~]# dkk=1
[Email protected] ~]# export DKK
[[Email protected] ~]# exit
Exit
[Email protected] ~]# echo $DKK
No value
The answer is: no ...
To achieve the words: There are several ways to come from http://blog.csdn.net/dreamcoding/article/details/8519689
So what can a child shell do to pass its own variables to the parent shell? The following methods can be considered:
Through an intermediate file:
#!/bin/bash (subvar= "Hello Shell" echo "$subvar" > Temp.txt) Read Pvar < Temp.txtecho $pvar Run output: $ sh Subandp.shhello Shell
Replace with command:
#!/bin/bashpvar= ' subvar= "Hello Shell"; Echo $subvar ' echo $pvar
-
Run Output:::
-
$./subandp.shhello Shell
The command that executes the command substitution (two anti-single quotes) is also done in the child shell.
Using Named pipes:
#!/bin/bashmkfifo-m 777 Npipe ( subsend= "Hello World" echo "$subsend" > Npipe &) Read Pread < Npipeecho "$pread" Exit 0
Run output:
[Email protected]:~/shell$./var.shhello World
About the famous pipe creation command Mkfifo can be consulted: http://www.groad.net/bbs/read.php?tid-3707.html
Use here Documentation:
#!/bin/bashread pvar << here ' subvar= "Hello Shell" echo $subvar ' Hereecho $pvar
Run output:
$./subandp.shhello Shell
There should be a lot of methods, the essential principle of these methods is based on interprocess communication.
take a look at the difference between Su and Su-switching users
Su method
[Email protected] ~]# Useradd test
[Email protected] ~]# test1=1
[email protected] ~]# su test
[Email protected] root]$ echo $test 1
No value
However, it is possible to transfer variables using export
[Email protected] ~]# export test=1
[email protected] ~]# su test
[Email protected] root]$ echo $test
1
[Email protected] root]$ echo $PATH
/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin -----Environment variables are the same as root environment variables
Take a look at the Su-method
[Email protected] ~]# su-test
[Email protected] ~]$ echo $test
No value
[Email protected] ~]$ echo $test 1
No value
[Email protected] ~]$ echo $PATH
/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/home/test/bin------------ environment variable differs from root environment variable
Comprehensive complaint: