Desh__
Desh__

Reputation: 899

Handling spaces with 'cp'

I've got an external drive with over 1TB of project files on it. I need to reformat this drive so I can reorganize it, however before I do that I need to transfer everything. The issue is I'm on a Mac and the drive is formatted as NTFS so all I can do is copy from it. I have tried to simply just copy and paste in Finder but the drive seems to lock up after roughly 15 min of copying that way. So I decided to write a bash script to iterate through the all 1000+ files one at a time. This seems to work for files that are without spaces but skips when it hits one.

Here is what I've hacked together so far.. I'm not too advanced in bash so any suggestions would be great on how you handle the spaces.

quota=800
size=`du -sg /Users/work/Desktop/TEMP`
files="/Volumes/Lacie/EXR_files/*"

for file in $files
do
    if [[ ${size%%$'\t'*} -lt $quota ]];
    then
        echo still under quota;
        cp -v $file /Users/work/Desktop/TEMP_EXR;
        du -sg /Users/work/Desktop/TEMP_EXR;
    else
        echo over quota;
    fi
done

(I'm checking for directory size because I'm having to split this temporary copy onto a few different place before I copy it all back onto the one reformatted drive.)

Upvotes: 1

Views: 302

Answers (2)

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57660

Hope I'm not misunderstanding. If you have problem with space character in filename, quote it. If you want bash to expand parameters inside it, use double quote.

cp -v "$file" /Users/work/Desktop/TEMP_EXR

Upvotes: 5

chepner
chepner

Reputation: 531325

You can put all the file names in an array, then iterate over that.

quota=800
size=`du -sg /Users/work/Desktop/TEMP`
files=( /Volumes/Lacie/EXR_files/* )

for file in "${files[@]}"
do
    if [[ ${size%%$'\t'*} -lt $quota ]];
    then
        echo still under quota;
        cp -v "$file" /Users/work/Desktop/TEMP_EXR;
        du -sg /Users/work/Desktop/TEMP_EXR;
    else
        echo over quota;
    fi
done

The two things to note are 1) quoting the array expansion in the for list, and 2) quoting $file for the cp command.

Upvotes: 0

Related Questions