I need to interactively (i.e. rm -i) remove files stored in variable $to_remove (one path per line). Unfortunately my code doesn't work because standard input is already used by redirection <<< "$to_remove".

while read -r f ; do
    rm -ir "$f"
done <<< "$to_remove"

How can I fix it?


UPDATE: Given that find is the source of the data, I would use an array instead:

readarray -t to_remove < <(find ...)
rm -i "${to_remove[@]}"

If you are a pre-4 version of bash, use this loop to fill the array.

while IFS= read -r fname; do
done < <(find ...)

None of these work with with files that contain newlines, but I find that case easier to ignore when possible, although in bash 4, you can dispense with the call to find altogether:

shopt -s nullglob globstar
to_remove=( "$WORKING_PATH"/**/* )

I assume you're populating to_remove from a file. Don't do that; read directly from the file.

while IFS= read -r fname <&3; do
    rm -i "$fname"
done 3< file.txt

This also uses a separate file descriptor to read from the file so that standard input can be used by rm.

(If you are truly stuck reading from to_remove, I would just use a temporary file:

printf "%s" "$to_remove" > tmp.txt
while IFS= read -r fname <&3; do
    rm -i "$fname"
done 3< tmp.txt
rm tmp.txt


  • No. $to_remove is defined like this: $to_remove=`find $WORKING_PATH -empty -print`. Afterwards $to_remove is processed. I save result of find in variable in order to not call find twice: $to_remove=`find $WORKING_PATH -empty -print`. $number_of_files=`find $WORKING_PATH -empty -print | wc -l`. – patryk.beza Aug 13 '15 at 15:53

I figured it out.

for f in `echo "$to_remove"` ; do
    rm -ir "$f"

Short version:

rm -ir "$to_remove"

Those two versions works as expected.

Strange enough the following code doesn't work:

for f in "$to_remove" ; do
    rm -ir "$f"


  • 1
    In the first example, the result of the command substitution undergoes word-splitting. In the second example, the quoted parameter expansion does not. Either way, you shouldn't be storing file names in a flat string parameter; it won't work if any of the file names contain newlines or other non-whitespace characters interpreted by the shell. – chepner Aug 13 '15 at 15:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.