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

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.

主站蜘蛛池模板: 淮滨县| 偃师市| 安义县| 桐乡市| 三河市| 富平县| 绥芬河市| 嘉峪关市| 连江县| 卢湾区| 怀集县| 富源县| 涿州市| 桦南县| 吴川市| 中卫市| 宽城| 金溪县| 南雄市| 株洲市| 东莞市| 陆良县| 乐山市| 中山市| 静宁县| 革吉县| 凭祥市| 四川省| 澄江县| 全州县| 城口县| 伊川县| 景东| 牟定县| 定西市| 祁门县| 启东市| 河曲县| 镇赉县| 西吉县| 淮阳县|