1

I have the following script:

ls -l | while read permissions number user user2 size month day hour filename
  do
    if [[ "$filename" == *foo* ]]
    then
      scount=`expr $scount + $size`
    fi
  done
echo $scount

The script checks the filename and size of the files in my folder, then it checks for files which contain 'foo' word, then it takes it size and adds it.

I have the following problem, if I call the scount variable from inside the loop it displays the numbers, but when it is outside it shows nothing, as if the variable does not exist. Does it have something to do with shell sessions? How can I display the variable outside of the loop?

user3214667
  • 57
  • 1
  • 1
  • 2
  • Just a guess, but maybe you have to declare your variable outside the loop :-) – sridesmet Apr 01 '14 at 10:49
  • 5
    You are manipulating the variable in a subshell. Refer to the linked question for an answer. – devnull Apr 01 '14 at 10:51
  • As a sidenote: rather use `stat` instead of `ls` in order to parse information about files. And if you want to calculate the size of a given amount of files then have a look at `du`. – Saucier Apr 01 '14 at 10:53
  • @devnull is correct - the subshell is the issue. It might suit your purposes better to loop over the results of find: `for f in $(find /my/dir -name "*foo*"); do ... done` and use `stat` to get the size of each `$f`. – Josh Jolly Apr 01 '14 at 10:54
  • Thank you Josh. I will definitely check devnull reference and rewrite my code using find and stat. – user3214667 Apr 01 '14 at 11:06

1 Answers1

1

Your while loop was run in a subshell so its variables are not visible outside. Try this one:

#!/bin/bash

while read current; do
   echo "current: $current"
   last=$current
done < <(echo -e "foo\nbar\nbaz")

echo "last: $last"
pawel7318
  • 3,383
  • 2
  • 28
  • 44
  • Thank you. I have already rewritten the code using advices from Josh Jolly and devnull and now it functions properly. Thank you all. – user3214667 Apr 01 '14 at 11:37