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?

5
  • Just a guess, but maybe you have to declare your variable outside the loop :-) Commented Apr 1, 2014 at 10:49
  • 5
    You are manipulating the variable in a subshell. Refer to the linked question for an answer. Commented Apr 1, 2014 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. Commented Apr 1, 2014 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. Commented Apr 1, 2014 at 10:54
  • Thank you Josh. I will definitely check devnull reference and rewrite my code using find and stat. Commented Apr 1, 2014 at 11:06

1 Answer 1

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"
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I have already rewritten the code using advices from Josh Jolly and devnull and now it functions properly. Thank you all.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.