user5552734
user5552734

Reputation:

How can I get the value out of this "while read" loop in Bash?

So I have this loop

    largest=0
    find $path -type f |  while read line; do
            largest=$(stat -c '%s' $line)
    done | sort -nr | head -1
    echo $largest

but the variable gets reset after the loop because of the bash subshell thing.

Is there a simple fix I could use to get this variable out?

Upvotes: 0

Views: 200

Answers (2)

Anthony Geoghegan
Anthony Geoghegan

Reputation: 11983

The problem with the code in the question is that the while loop result runs in a subshell by virtue of the fact that it’s part of a pipeline command. Then, when the subshell exits the value of largest is lost.

Since you’re using GNU/Linux (with GNU find), you can use its -printf option to greatly simplify your command and avoid the unnecessary process forks (to run stat) – and the inefficiency of the while loop.

find $path -type f -printf "%s\n"  | sort -nr | head -1

Upvotes: 1

Zang MingJie
Zang MingJie

Reputation: 5275

largest=`find $path -type f |  while read line; do
        stat -c '%s' $line
done | sort -nr | head -1`
echo $largest

Upvotes: 0

Related Questions