Search code examples
bashshellmvfile-management

Shell Script Removes Some of the Files


I have a neural-network project for classifying flowers. I have a dataset of flowers and I want to rename for example all daisy images as daisy1, daisy2, and so on. I wrote a shell script in order to do that, but I noticed that every time I ran the script some of the images were lost and I don't understand why. Any idea? Here is my script:

(( i = 1 )) 

for file in $(ls)
do
[ "$file" != "change-filenames.sh" ] && mv "$file" "daisy$i" && (( i++ ))
done

Solution

  • I see two risky issues in your code:

    (1) You are using ls to generate a list of filenames (which would produce weird results if, for instance, a filename contains spaces).

    (2) Say that your directory contains initially the files abc and daisyabc1. The first renaming would be a mv abc daisyabc1, hence destroying the original daisyabc1. The second renaming would then be a mv daisyabc1 daisydaisyabc2, and you would end up with only one file where you originally had two. I guess this is the cause of your loss of files.

    BTW, your counter (i) does not get incremented if the mv fails. I don't know if this is a bug or is so by design.