I have a script that process a folder, and count the files in the mean time.
i=1 find tmp -type f | while read x do i=$(($i + 1)) echo $i done echo $i
However, $i is always 1, how do I resolve this?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
In your example the while-loop is executed in a subshell, so changes to the variable inside the while-loop won’t affect the external variable. This is because you’re using the loop with a pipe, which automatically causes it to run in a subshell.
Here is an alternative solution using a while loop:
i=1 while read x; do i=$(($i + 1)) echo $i done <<<$(find tmp -type f) echo $i
And here is the same approach using a for-loop:
i=1 for x in $(find tmp -type f); do i=$(($i + 1)) echo $i done echo $i
For more information see the following posts:
Also look at the following chapter from the Advanced Bash Scripting Guide:
Method 2
#!/bin/bash i=1 while read x do i=$((i+1)) echo $i done < <(find . -type f) echo $i
https://stackoverflow.com/questions/7390497/bash-propagate-value-of-variable-to-outside-of-the-loop
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0