LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Case statements and vars for bash script (https://www.linuxquestions.org/questions/programming-9/case-statements-and-vars-for-bash-script-696156/)

geech 01-09-2009 02:46 PM

Case statements and vars for bash script
 
Can someone please tell me why when this runs that ZIP and FILE are echo'd as nulls at the end? The file test.txt has tons of stuff in it.

FILENAME=test.txt
count=0
cat $FILENAME | while read LINE
do
count=`expr "$count" + 1`
case $count in
"1") ZIP=$LINE;;
"2") FILE=$LINE;;
*)
esac
done
echo $ZIP
echo $FILE

antegallya 01-09-2009 04:49 PM

Hello,
it is because when you use a pipe bash start a subshell to execute the while read ...
and so you are not under the scope of your ZIP and FILE variables when you try to echo them and then you get null.
To avoid this you can use a 'for' instead :
Code:

FILENAME=test.txt
count=0
for LINE in "$(cat $FILENAME)"
 do
  count=`expr "$count" + 1`
  case $count in
    "1") ZIP=$LINE;;
    "2") FILE=$LINE;;
    *)
  esac
 done
echo $ZIP
echo $FILE



All times are GMT -5. The time now is 03:32 PM.