Monday, July 27, 2009

Assignment 6 - Issue.

Apparently, Shaula is running an older version of #bash which has issues with variable scope - in our code snippet:

#!/bin/bash
#sample code for reading in a file line by line.
fileIn=$1

cat $fileIn | while read linein
do
echo $linein
done

the piping into the while statement causes the while-loop to run in a subshell, any variables declared above the 'do' will exist in one shell, any variables used between the 'do' and the 'done' will be declared in another. In other words, when the script exits the subshell, variables will be reset to their values prior to entering the while loop. We can fix it by doing this:

while read linein
do
echo $linein
done < $fileIn

This causes the script to execute within one shell, therefore the variable scope is maintained for the whole script.

Good Luck!

No comments:

Post a Comment