0

I have a directory structure like this:

|--Photos  
   |--2014-01-15 #2  
      |--IMG_0045.JPG  
      |--IMG_0051.JPG  
   |--2014-06-19  
      |--IMG_0078.JPG  

Notice one folder's name contains a space [ 2014-01-15 #2 ]. I wrote a bash script to move only the *.JPG files in all the folders using this:

#!/bin/bash
for i in $(ls); do  
    if [ -d $i ]; then
        cd $i
        mv *.JPG /opt/data/tmp/
        cd -
    fi
done  

I understand that the script didn't go into the folders with names that contained spaces because of word splitting.

Is there a bash script you could write in order to move *.JPG files from all folders?

rhombus
  • 13
  • 4

1 Answers1

1

Simply mv */*.JPG /opt/data/tmp will do what you ask.

Your script has two common beginner errors. You need to put double quotes around all variables which contain file names, and you should not be using ls to find files.

Personally, I would also advise against using cd in most scripts.

If you need to loop over directories in other scripts, for i in ./*/; do... does that.

If you need to recurse arbitrarily deeply nested directories, find does that. With GNU find and GNU mv, find dir -type f -name '*.JPG' -exec mv -t /opt/data/tmp {} +

tripleee
  • 175,061
  • 34
  • 275
  • 318