I am writing a bash script that deletes all the files whose paths are given in delete.txt. delete.txt is thousands of lines long, each line has a path that is structured like this:
Abies concolor/images/FV-GFVM-725_crop.jpg
Where there is a space in the name of the first directory.
Currently, my bash script reads each line of delete.txt, saves it to$line and deletes it.
#!/bin/bash
while IFS='' read -r line || [[ -n "$line" ]]; do
"rm $line"
done < "$1"
However, because there is a space in the first directory name, my rm command returns:
rm Abies concolor/images/FV-GFVM-725_crop.jpg: No such file or directory
What can I do in my bash script to add a quote before the first and after the second words of each line before doing the rm command?
Advertisement
Answer
The problem is with rm invocation. Just correctly quote line variable:
#!/bin/bash while IFS='' read -r line || [[ -n "$line" ]]; do rm "$line" done < "$1"
Or, even simpler, you can use xargs and this oneliner which replaces the complete script:
cat delete.txt | xargs -I{} rm '{}'
This will run rm for each line in delete.txt, properly quoted. The trick here is to use -I <placeholder> option which will make sure the command rm '<placeholder>' is executed once per line (not word), each time substituting <placeholder> with filename from current line.