Tuesday, October 6, 2009

Paranthesis () in shell script

Parenthesis () within commands inside shell script indicates the list of commands as a command group.

A listing of commands inside shell script start a subsell. Variables within subshell is not visible from rest of the script. Within subshell main shell variables can be visible but the parent process which means the script cannot read variables created in the child process, the subshell.

Example:

$ cat >subshell.sh
var=10
(echo $var; var=11 ; echo $var)
echo $var

$ sh subshell.sh
10
11
10

From the example we see within subshell the value of variable var is changed but that value is not affected within main shell. And the variable of main shell can be accessed by the subshell.

- Parenthesis is used for array declaration.

$ cat >array_shell.sh
array_var=(one two three)
for (( i = 0 ; i < ${#array_var[@]} ; i++ ))
do echo ${array_var[$i]}
done

$ sh array_shell.sh
one two three


In this example, the value ${#array_var[@]} evaluates into the number of elements in the array (3 in this case). The individual elements of the array are accessed, one at a time, using the index integer $i as ${array_var[$i]}

No comments:

Post a Comment