Friday, May 30, 2008

Concept of Sub-Shells - Part1

First & foremost to create sub-shells within a script you need to use round brackets "( )". Value assigned to outermost shell is always 0. As you move inside sub-shells their values keep on increasing by 1 as depicted in the example shown below:

#!/bin/bash
#Author: Parag Kalra
#Date: 31st May, 2008
#Name: subshell1.sh
#Usage: ./subshell1.sh
#Purpose: To illustrate values assigned to sub-shells

echo "We are outside the subshell."
echo "Subshell level OUTSIDE subshell = $BASH_SUBSHELL"


(
echo "We are inside first subshell."
echo "Subshell level INSIDE first subshell = $BASH_SUBSHELL"

(
echo "Inside second sub-shell"
echo "Subshell level INSIDE second subshell = $BASH_SUBSHELL"



(
echo "Inside third sub-shell"
echo "Subshell level INSIDE third subshell = $BASH_SUBSHELL"
)


)

)

echo "We are again outside all the subshells."
echo "Subshell level OUTSIDE subshell = $BASH_SUBSHELL"

#END OF SCRIPT

The output of above script is:

We are outside the subshell.
Subshell level OUTSIDE subshell = 0
We are inside first subshell.
Subshell level INSIDE first subshell = 1
Inside second sub-shell
Subshell level INSIDE second subshell = 2
Inside third sub-shell
Subshell level INSIDE third subshell = 3
We are again outside all the subshells.
Subshell level OUTSIDE subshell = 0

No comments: