Search code examples
bashloopswhile-loopifs

While, do, done flow control in bash


Can anyone explain the control flow of the following bash script?

while IFS= read -r file
do 
rm -rf "$file"
done < todelete.txt

From what I understand, this would happen:

IFS would be assigned nothing. The rm -rf command would do nothing because its argument, the variable $file, is blank/empty/nothing. The two previous steps would then repeat indefinitely.

Clearly this is not the case, because the script works as expected; it deletes all files listed in todelete.txt.

I believe the explanation lies in "done < todelete.txt" but I don't understand what's happening there.


Solution

  • The redirect after done affects read's input stream. So read will work on the contents of todelete.txt rather than stdin.

    You should read the Internal Commands section of the Bash manual for more info. (Browse directly to example 15-7.)