1

This question already has an answer here:

My code

var=34
find $1 -type f | while read line;
do
        file_status=`file  "$line"`
        file_name=`echo $line | sed s/".*\/"//g`
        line_length=${#file_name}
        if [ $line_length -gt $n ]; then
                echo "hi there"
                var=$((var+1))
        fi
done
echo $var

I can see the message hi there for multiple times, but my variable will be 34 after i'm done with the while loop.

marked as duplicate by Jeff Schaller, slm bash Apr 4 '16 at 16:39

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1

Because you have used a pipe (|) and commands around pipe are run in subshells.

So the value of variable var is changed (incremented) in the relevant subshell and gone out of scope as the subshell exits, so it will have no impact on parent shell's value, hence the parent shell will still have the value 34.


To solve this, you can use process substitution to run find:

var=34
while read line; do
        file_status=`file  "$line"`
        file_name=`echo $line | sed s/".*\/"//g`
        line_length=${#file_name}
        if [ $line_length -gt $n ]; then
                echo "hi there"
                var=$((var+1))
        fi
done < <(find $1 -type f)
echo $var
  • How can I do a quick fix for this issue? – user1452079 Apr 4 '16 at 15:39
  • @user1452079 Check my edits.. – heemayl Apr 4 '16 at 15:48

Not the answer you're looking for? Browse other questions tagged or ask your own question.