1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML
><HEAD
><TITLE
>Subshells</TITLE
><META
NAME="GENERATOR"
CONTENT="Modular DocBook HTML Stylesheet Version 1.76b+
"><LINK
REL="HOME"
TITLE="Advanced Bash-Scripting Guide"
HREF="index.html"><LINK
REL="UP"
TITLE="Advanced Topics"
HREF="part5.html"><LINK
REL="PREVIOUS"
TITLE="Applications"
HREF="redirapps.html"><LINK
REL="NEXT"
TITLE="Restricted Shells"
HREF="restricted-sh.html"><META
HTTP-EQUIV="Content-Style-Type"
CONTENT="text/css"><LINK
REL="stylesheet"
HREF="common/kde-common.css"
TYPE="text/css"><META
HTTP-EQUIV="Content-Type"
CONTENT="text/html; charset=iso-8859-1"><META
HTTP-EQUIV="Content-Language"
CONTENT="en"><LINK
REL="stylesheet"
HREF="common/kde-localised.css"
TYPE="text/css"
TITLE="KDE-English"><LINK
REL="stylesheet"
HREF="common/kde-default.css"
TYPE="text/css"
TITLE="KDE-Default"></HEAD
><BODY
CLASS="CHAPTER"
BGCOLOR="#FFFFFF"
TEXT="#000000"
LINK="#AA0000"
VLINK="#AA0055"
ALINK="#AA0000"
STYLE="font-family: sans-serif;"
><DIV
CLASS="NAVHEADER"
><TABLE
SUMMARY="Header navigation table"
WIDTH="100%"
BORDER="0"
CELLPADDING="0"
CELLSPACING="0"
><TR
><TH
COLSPAN="3"
ALIGN="center"
>Advanced Bash-Scripting Guide: An in-depth exploration of the art of shell scripting</TH
></TR
><TR
><TD
WIDTH="10%"
ALIGN="left"
VALIGN="bottom"
><A
HREF="redirapps.html"
ACCESSKEY="P"
>Prev</A
></TD
><TD
WIDTH="80%"
ALIGN="center"
VALIGN="bottom"
></TD
><TD
WIDTH="10%"
ALIGN="right"
VALIGN="bottom"
><A
HREF="restricted-sh.html"
ACCESSKEY="N"
>Next</A
></TD
></TR
></TABLE
><HR
ALIGN="LEFT"
WIDTH="100%"></DIV
><DIV
CLASS="CHAPTER"
><H1
><A
NAME="SUBSHELLS"
></A
>Chapter 21. Subshells</H1
><P
><A
NAME="SUBSHELLSREF"
></A
></P
><P
>Running a shell script launches a new process, a
<I
CLASS="FIRSTTERM"
>subshell</I
>.</P
><TABLE
CLASS="SIDEBAR"
BORDER="1"
CELLPADDING="5"
><TR
><TD
><DIV
CLASS="SIDEBAR"
><A
NAME="AEN18083"
></A
><P
><TT
CLASS="USERINPUT"
><B
>Definition:</B
></TT
>
A <I
CLASS="FIRSTTERM"
>subshell</I
> is a
<A
HREF="othertypesv.html#CHILDREF2"
>child process</A
> launched by a
shell (or <I
CLASS="FIRSTTERM"
>shell script</I
>).</P
></DIV
></TD
></TR
></TABLE
><P
>A subshell is a separate instance of the command processor
-- the <I
CLASS="FIRSTTERM"
>shell</I
> that gives you the prompt at
the console or in an <I
CLASS="FIRSTTERM"
>xterm</I
> window. Just
as your commands are interpreted at the command-line prompt,
similarly does a script <A
HREF="timedate.html#BATCHPROCREF"
>batch-process</A
> a list of
commands. Each shell script running is, in effect, a subprocess
(<I
CLASS="FIRSTTERM"
>child process</I
>) of the <A
HREF="internal.html#FORKREF"
>parent</A
> shell.</P
><P
>A shell script can itself launch subprocesses. These
<I
CLASS="FIRSTTERM"
>subshells</I
> let the script do
parallel processing, in effect executing multiple subtasks
simultaneously.</P
><P
> <TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 #!/bin/bash
2 # subshell-test.sh
3
4 (
5 # Inside parentheses, and therefore a subshell . . .
6 while [ 1 ] # Endless loop.
7 do
8 echo "Subshell running . . ."
9 done
10 )
11
12 # Script will run forever,
13 #+ or at least until terminated by a Ctl-C.
14
15 exit $? # End of script (but will never get here).
16
17
18
19 Now, run the script:
20 sh subshell-test.sh
21
22 And, while the script is running, from a different xterm:
23 ps -ef | grep subshell-test.sh
24
25 UID PID PPID C STIME TTY TIME CMD
26 500 2698 2502 0 14:26 pts/4 00:00:00 sh subshell-test.sh
27 500 2699 2698 21 14:26 pts/4 00:00:24 sh subshell-test.sh
28
29 ^^^^
30
31 Analysis:
32 PID 2698, the script, launched PID 2699, the subshell.
33
34 Note: The "UID ..." line would be filtered out by the "grep" command,
35 but is shown here for illustrative purposes.</PRE
></TD
></TR
></TABLE
>
</P
><P
>In general, an <A
HREF="external.html#EXTERNALREF"
>external
command</A
> in a script <A
HREF="internal.html#FORKREF"
>forks
off</A
> a subprocess,
<A
NAME="AEN18102"
HREF="#FTN.AEN18102"
>[1]</A
>
whereas a Bash <A
HREF="internal.html#BUILTINREF"
>builtin</A
>
does not. For this reason, builtins execute more quickly
and use fewer system resources than their external command
equivalents.</P
><DIV
CLASS="VARIABLELIST"
><P
><B
><A
NAME="SUBSHELLPARENS1"
></A
>Command List within
Parentheses</B
></P
><DL
><DT
>( command1; command2; command3; ... )</DT
><DD
><P
>A command list embedded between
<TT
CLASS="REPLACEABLE"
><I
>parentheses</I
></TT
> runs as a
subshell.</P
></DD
></DL
></DIV
><P
><A
NAME="PARVIS"
></A
>Variables in a subshell are
<SPAN
CLASS="emphasis"
><I
CLASS="EMPHASIS"
>not</I
></SPAN
> visible outside the block of code
in the subshell. They are not accessible to the <A
HREF="internal.html#FORKREF"
>parent process</A
>, to the shell
that launched the subshell. These are, in effect,
variables <A
HREF="localvar.html#LOCALREF"
>local</A
> to the
<I
CLASS="FIRSTTERM"
>child process</I
>.</P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="SUBSHELL"
></A
><P
><B
>Example 21-1. Variable scope in a subshell</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 #!/bin/bash
2 # subshell.sh
3
4 echo
5
6 echo "We are outside the subshell."
7 echo "Subshell level OUTSIDE subshell = $BASH_SUBSHELL"
8 # Bash, version 3, adds the new $BASH_SUBSHELL variable.
9 echo; echo
10
11 outer_variable=Outer
12 global_variable=
13 # Define global variable for "storage" of
14 #+ value of subshell variable.
15
16 (
17 echo "We are inside the subshell."
18 echo "Subshell level INSIDE subshell = $BASH_SUBSHELL"
19 inner_variable=Inner
20
21 echo "From inside subshell, \"inner_variable\" = $inner_variable"
22 echo "From inside subshell, \"outer\" = $outer_variable"
23
24 global_variable="$inner_variable" # Will this allow "exporting"
25 #+ a subshell variable?
26 )
27
28 echo; echo
29 echo "We are outside the subshell."
30 echo "Subshell level OUTSIDE subshell = $BASH_SUBSHELL"
31 echo
32
33 if [ -z "$inner_variable" ]
34 then
35 echo "inner_variable undefined in main body of shell"
36 else
37 echo "inner_variable defined in main body of shell"
38 fi
39
40 echo "From main body of shell, \"inner_variable\" = $inner_variable"
41 # $inner_variable will show as blank (uninitialized)
42 #+ because variables defined in a subshell are "local variables".
43 # Is there a remedy for this?
44 echo "global_variable = "$global_variable"" # Why doesn't this work?
45
46 echo
47
48 # =======================================================================
49
50 # Additionally ...
51
52 echo "-----------------"; echo
53
54 var=41 # Global variable.
55
56 ( let "var+=1"; echo "\$var INSIDE subshell = $var" ) # 42
57
58 echo "\$var OUTSIDE subshell = $var" # 41
59 # Variable operations inside a subshell, even to a GLOBAL variable
60 #+ do not affect the value of the variable outside the subshell!
61
62
63 exit 0
64
65 # Question:
66 # --------
67 # Once having exited a subshell,
68 #+ is there any way to reenter that very same subshell
69 #+ to modify or access the subshell variables?</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
>See also <A
HREF="variables2.html#BASHPIDREF"
>$BASHPID</A
> and
<A
HREF="gotchas.html#SUBPIT"
>Example 34-2</A
>.</P
><TABLE
CLASS="SIDEBAR"
BORDER="1"
CELLPADDING="5"
><TR
><TD
><DIV
CLASS="SIDEBAR"
><A
NAME="AEN18127"
></A
><P
><A
NAME="SCOPEREF"
></A
></P
><P
><TT
CLASS="USERINPUT"
><B
>Definition:</B
></TT
> The
<I
CLASS="FIRSTTERM"
>scope</I
> of a variable is the
context in which it has meaning, in which it has a
<I
CLASS="FIRSTTERM"
>value</I
> that can be referenced. For
example, the scope of a <A
HREF="localvar.html#LOCALREF1"
>local
variable</A
> lies only within the function,
block of code, or subshell within which it is defined,
while the scope of a <I
CLASS="FIRSTTERM"
>global</I
> variable
is the entire script in which it appears.</P
></DIV
></TD
></TR
></TABLE
><P
><A
NAME="SUBSHNLEVREF"
></A
></P
><DIV
CLASS="NOTE"
><TABLE
CLASS="NOTE"
WIDTH="100%"
BORDER="0"
><TR
><TD
WIDTH="25"
ALIGN="CENTER"
VALIGN="TOP"
><IMG
SRC="common/note.png"
HSPACE="5"
ALT="Note"></TD
><TD
ALIGN="LEFT"
VALIGN="TOP"
><P
>While the <A
HREF="variables2.html#BASHSUBSHELLREF"
>$BASH_SUBSHELL</A
>
internal variable indicates the nesting level of a
subshell, the <A
HREF="variables2.html#SHLVLREF"
>$SHLVL</A
>
variable <SPAN
CLASS="emphasis"
><I
CLASS="EMPHASIS"
>shows no change</I
></SPAN
> within
a subshell.</P
><P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 echo " \$BASH_SUBSHELL outside subshell = $BASH_SUBSHELL" # 0
2 ( echo " \$BASH_SUBSHELL inside subshell = $BASH_SUBSHELL" ) # 1
3 ( ( echo " \$BASH_SUBSHELL inside nested subshell = $BASH_SUBSHELL" ) ) # 2
4 # ^ ^ *** nested *** ^ ^
5
6 echo
7
8 echo " \$SHLVL outside subshell = $SHLVL" # 3
9 ( echo " \$SHLVL inside subshell = $SHLVL" ) # 3 (No change!)</PRE
></TD
></TR
></TABLE
>
</P
></TD
></TR
></TABLE
></DIV
><P
>Directory changes made in a subshell do not carry over to the
parent shell.</P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="ALLPROFS"
></A
><P
><B
>Example 21-2. List User Profiles</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 #!/bin/bash
2 # allprofs.sh: Print all user profiles.
3
4 # This script written by Heiner Steven, and modified by the document author.
5
6 FILE=.bashrc # File containing user profile,
7 #+ was ".profile" in original script.
8
9 for home in `awk -F: '{print $6}' /etc/passwd`
10 do
11 [ -d "$home" ] || continue # If no home directory, go to next.
12 [ -r "$home" ] || continue # If not readable, go to next.
13 (cd $home; [ -e $FILE ] && less $FILE)
14 done
15
16 # When script terminates, there is no need to 'cd' back to original directory,
17 #+ because 'cd $home' takes place in a subshell.
18
19 exit 0</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
>A subshell may be used to set up a <SPAN
CLASS="QUOTE"
>"dedicated
environment"</SPAN
> for a command group.
<TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 COMMAND1
2 COMMAND2
3 COMMAND3
4 (
5 IFS=:
6 PATH=/bin
7 unset TERMINFO
8 set -C
9 shift 5
10 COMMAND4
11 COMMAND5
12 exit 3 # Only exits the subshell!
13 )
14 # The parent shell has not been affected, and the environment is preserved.
15 COMMAND6
16 COMMAND7</PRE
></TD
></TR
></TABLE
>
As seen here, the <A
HREF="internal.html#EXITREF"
>exit</A
>
command only terminates the subshell in which it is running,
<SPAN
CLASS="emphasis"
><I
CLASS="EMPHASIS"
>not</I
></SPAN
> the parent shell or script.</P
><P
>One application of such a <SPAN
CLASS="QUOTE"
>"dedicated environment"</SPAN
>
is testing whether a variable is defined.
<TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 if (set -u; : $variable) 2> /dev/null
2 then
3 echo "Variable is set."
4 fi # Variable has been set in current script,
5 #+ or is an an internal Bash variable,
6 #+ or is present in environment (has been exported).
7
8 # Could also be written [[ ${variable-x} != x || ${variable-y} != y ]]
9 # or [[ ${variable-x} != x$variable ]]
10 # or [[ ${variable+x} = x ]]
11 # or [[ ${variable-x} != x ]]</PRE
></TD
></TR
></TABLE
></P
><P
>Another application is checking for a lock file:
<TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 if (set -C; : > lock_file) 2> /dev/null
2 then
3 : # lock_file didn't exist: no user running the script
4 else
5 echo "Another user is already running that script."
6 exit 65
7 fi
8
9 # Code snippet by Stphane Chazelas,
10 #+ with modifications by Paulo Marcel Coelho Aragao.</PRE
></TD
></TR
></TABLE
>
</P
><P
>+</P
><P
>Processes may execute in parallel within different
subshells. This permits breaking a complex task into subcomponents
processed concurrently.</P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="PARALLEL-PROCESSES"
></A
><P
><B
>Example 21-3. Running parallel processes in subshells</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 (cat list1 list2 list3 | sort | uniq > list123) &
2 (cat list4 list5 list6 | sort | uniq > list456) &
3 # Merges and sorts both sets of lists simultaneously.
4 # Running in background ensures parallel execution.
5 #
6 # Same effect as
7 # cat list1 list2 list3 | sort | uniq > list123 &
8 # cat list4 list5 list6 | sort | uniq > list456 &
9
10 wait # Don't execute the next command until subshells finish.
11
12 diff list123 list456</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
>Redirecting I/O to a subshell uses the <SPAN
CLASS="QUOTE"
>"|"</SPAN
> pipe
operator, as in <TT
CLASS="USERINPUT"
><B
>ls -al | (command)</B
></TT
>.</P
><DIV
CLASS="NOTE"
><TABLE
CLASS="NOTE"
WIDTH="100%"
BORDER="0"
><TR
><TD
WIDTH="25"
ALIGN="CENTER"
VALIGN="TOP"
><IMG
SRC="common/note.png"
HSPACE="5"
ALT="Note"></TD
><TD
ALIGN="LEFT"
VALIGN="TOP"
><P
>A code block between <A
HREF="special-chars.html#CODEBLOCKREF"
>curly brackets</A
> does
<SPAN
CLASS="emphasis"
><I
CLASS="EMPHASIS"
>not</I
></SPAN
> launch a subshell.</P
><P
>{ command1; command2; command3; . . . commandN; }</P
><P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 var1=23
2 echo "$var1" # 23
3
4 { var1=76; }
5 echo "$var1" # 76</PRE
></TD
></TR
></TABLE
></P
></TD
></TR
></TABLE
></DIV
></DIV
><H3
CLASS="FOOTNOTES"
>Notes</H3
><TABLE
BORDER="0"
CLASS="FOOTNOTES"
WIDTH="100%"
><TR
><TD
ALIGN="LEFT"
VALIGN="TOP"
WIDTH="5%"
><A
NAME="FTN.AEN18102"
HREF="subshells.html#AEN18102"
>[1]</A
></TD
><TD
ALIGN="LEFT"
VALIGN="TOP"
WIDTH="95%"
><P
>An external command invoked with an <A
HREF="internal.html#EXECREF"
>exec</A
> does <SPAN
CLASS="emphasis"
><I
CLASS="EMPHASIS"
>not</I
></SPAN
>
(usually) fork off a subprocess / subshell.</P
></TD
></TR
></TABLE
><DIV
CLASS="NAVFOOTER"
><HR
ALIGN="LEFT"
WIDTH="100%"><TABLE
SUMMARY="Footer navigation table"
WIDTH="100%"
BORDER="0"
CELLPADDING="0"
CELLSPACING="0"
><TR
><TD
WIDTH="33%"
ALIGN="left"
VALIGN="top"
><A
HREF="redirapps.html"
ACCESSKEY="P"
>Prev</A
></TD
><TD
WIDTH="34%"
ALIGN="center"
VALIGN="top"
><A
HREF="index.html"
ACCESSKEY="H"
>Home</A
></TD
><TD
WIDTH="33%"
ALIGN="right"
VALIGN="top"
><A
HREF="restricted-sh.html"
ACCESSKEY="N"
>Next</A
></TD
></TR
><TR
><TD
WIDTH="33%"
ALIGN="left"
VALIGN="top"
>Applications</TD
><TD
WIDTH="34%"
ALIGN="center"
VALIGN="top"
><A
HREF="part5.html"
ACCESSKEY="U"
>Up</A
></TD
><TD
WIDTH="33%"
ALIGN="right"
VALIGN="top"
>Restricted Shells</TD
></TR
></TABLE
></DIV
></BODY
></HTML
>
|