While, do, done flow control in bash
-
29-01-2021 - |
Pregunta
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.
Solución
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.)
Otros consejos
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.