1

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.

1 Answers1

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
heemayl
  • 56,300