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

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.

主站蜘蛛池模板: 黄石市| 将乐县| 武鸣县| 合山市| 建阳市| 兴仁县| 开封县| 大名县| 邛崃市| 达拉特旗| 彭阳县| 苍山县| 林芝县| 新沂市| 慈利县| 常熟市| 东方市| 嘉定区| 洛阳市| 桐梓县| 榆社县| 调兵山市| 应城市| 隆安县| 堆龙德庆县| 响水县| 桦甸市| 高平市| 阿城市| 绥化市| 社旗县| 富源县| 盐津县| 台前县| 香河县| 温宿县| 龙陵县| 南岸区| 连平县| 龙岩市| 绥阳县|