官术网_书友最值得收藏!

Exporting variables

We can use the export command to make variables available in the child process or subshell. But if we declare new variables in the child process and export it in the child process, the variable will not be available in parent process. The parent process can export variables to a child, but the child process cannot export variables to the parent process.

Whenever we create a Shell script and execute it, a new shell process is created and the Shell script runs in that process. Any exported variable values are available to the new shell or to any sub-process.

We can export any variable as follows:

$ export NAME

Or we can use this:

$ declare -x NAME

Let's try to understand the concept of exporting the variable, using the following example:

$ PERSON="Ganesh Naik"$ export PERSON$ echo $PERSONGanesh Naik$ echo $$515

The process ID of the current shell or parent shell is 515.

This will start a subshell:

$ bash

This is the process ID of new or sub-shell:

$ echo $$526

Let us check the presence of variables:

$ echo $PERSONGanesh Naik$ PERSON="Author"$ echo $PERSONAuthor$ exit

This will terminate the subshell, and it will be placed in the parent shell:

$ echo $$
515

This displays the presence of the variable in the original shell or parent shell:

$ echo $PERSONGanesh Naik

Let's write a shell script to use the concept we have learned:

# Ubuntu Timezone files location : /usr/share/zoneinfo/ 
# redhat "/etc/localtime"  instead of "/etc/timezone" 
# In Redhat 
# ln -sf /usr/share/zoneinfo/America/Los_Angeles /etc/localtime 
 
export TZ=America/Los_Angeles 
echo "Your Timezone is = $TZ" 
date 
export TZ=Asia/Tokyo 
echo "Your Timezone is = $TZ" 
date 
 
unset TZ 
 
echo "Your Timezone is = $(cat /etc/timezone)" 
# For Redhat or Fedora /etc/localtime 
date 

The date command checks the TZ environmental variable. We initialized the TZ for Los_Angeles, then to Tokyo, and, finally, we removed it. We can see the difference in the date command output.

Let's write another Shell script to study the parent and child process, and the export of variables.

Create the export1.sh shell script:

#!/bin/bash 
foo="The first variable foo" 
export bar="The second variable bar" 
./export2.sh 
 
Create another shell script export2.sh 
#!/bin/bash 
echo "$foo" 
echo "$bar" 

The shell script export1.sh runs as a parent process and export2.sh is started as a child process of export1.sh. We can clearly see that variable bar, which was exported, is available in the child process, but the variable foo, which was not exported, is not available in the child process.

主站蜘蛛池模板: 宣汉县| 大荔县| 舞钢市| 平顺县| 永年县| 惠来县| 赤水市| 建平县| 香格里拉县| 托克逊县| 大邑县| 井陉县| 河南省| 德钦县| 河西区| 宝坻区| 卢龙县| 循化| 江北区| 张北县| 宁津县| 偏关县| 东乌珠穆沁旗| 长垣县| 神农架林区| 息烽县| 韶山市| 镇江市| 台中市| 大关县| 岑巩县| 札达县| 万源市| 桐城市| 保德县| 宜城市| 隆回县| 轮台县| 富顺县| 山东| 阳山县|