Question

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.

Was it helpful?

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.)

OTHER TIPS

The whole while ... done is treated as single command, which is fed a todelete.txt file on its input.

The while IFS= read -r file thing reads the lines from this input file until the EOF, assigning each line to $file variable, and each iteration of the loop removes that file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top