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?
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
largest=`find $path -type f | while read line; do
stat -c '%s' $line
done | sort -nr | head -1`
echo $largest
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.