|
|
January
5, 2004 -
Subshells
& Subshell Grouping - Part I
|
|
Invoking
a shell script by entering only the
script's name on the command line creates
a subshell in which the script runs.
It is important to understand that the
subshell has a separate environment from
the login/parent shell.
Alternatively, prefacing the script name
with a "." (dot) and a space
causes the script to run within the
context of the login session, as if you
had typed each line of the script in at
the command prompt. A simple shell
script named display_info will be used to
demonstrate this concept:
|
[livefire@hawk] # cat display_info
print
ps -f
print
print "The value of x is: $x"
print
[livefire@hawk] #
|
|
Prior
to running display_info as a subshell, a
value will be assigned to the variable x,
and the current session's process
information will be displayed.
|
[livefire@hawk] # x=50
[livefire@hawk] # print $x
50
[livefire@hawk] # ps -f
UID PID PPID C STIME TTY TIME CMD
livefire 455 453 0 13:27:20 pts/2 0:00 -ksh
[livefire@hawk] #
[livefire@hawk] # display_info
UID PID PPID C STIME TTY TIME CMD
livefire 540 455 0 15:11:09 pts/2 0:00 -ksh
livefire 455 453 0 13:27:20 pts/2 0:00 -ksh
The value of x is:
[livefire@hawk] #
|
Notice
that a child process running another
instance of ksh (the Korn shell program) is
created, and the value assigned to the local
variable x in the parent shell is not
visible in the subshell. This time the
same script will be executed without
creating a subshell:
|
[livefire@hawk] # . display_info
UID PID PPID C STIME TTY TIME CMD
livefire 455 453 0 13:27:20 pts/2 0:00 -ksh
The value of x is: 50
[livefire@hawk] #
|
As
you can see from the output, a second
process is not created and the previously
defined value for x is displayed.
Next week we'll discuss when the Korn shell
creates and does not create subshells, and
why or why not you may want to use subshells.
|
|
|
|
|
|
|
|
|
|
|
Learn
more...
If you are new to the UNIX or Linux
operating system and would like to learn
more, you may want to consider
registering for LiveFire Labs' UNIX
and Linux Operating System Fundamentals
online training course.
If you already have a solid grasp of the
fundamentals but would like to learn more
about the Korn shell and basic and
advanced shell scripting, taking our Korn
Shell Scripting course will be
beneficial to you.
Our
innovative hands-on training model allows
you to learn
UNIX by completing hands-on
exercises on real servers in our Internet
Lab.
More
Tips...
· Popular
UNIX Tips from the Past
|
|
|
|
 |
 |
| |
Receive
the UNIX Tip, Trick, or Shell Script of the
Week by Email
|
|
|
|