I have a script I am trying to write to move customer files to a backup server. Because these are customer files, I have no control on how they are named. We need to be able to offload these to a backup server before we process them, but so far the script has issues handling any directory or file dropped in that has spaces in the name. I think it may be the way things are quoted in the script, or it may be something else, but I can't figure it out. I found several promising leads including:
How to deal with spaces in filenames
How to deal with file name starts with spaces in bash
However, going through all these and several other sources I have not been able to determine how to get it to work properly. The code is:
#! /bin/bash
# Get customer to search
CUSTOMER=$1
# Get destination
DESTINATION_FOLDER=$2
# Get desired older than age
AGE=60 # Age in days
if [[ -d "/home2/$CUSTOMER" ]]; then
cd "/home2/$CUSTOMER"
DEST="$DESTINATION_FOLDER"
if [[ ! -d "$DEST" ]]; then
mkdir -p $DEST
fi
TODAY=`date +%y%m%d`
echo "Starting to move files to $DEST" > /root/logs/${TODAY}archive2log
for DIRCONT in './'*; do
echo "$DIRCONT moving to dataoffload...."
SECONDS=$(($AGE * 3600 * 24)) # Turns days to seconds
FILEAGE=$((`date +%s` - `date -r "$DIRCONT" +%s`))
if [ $SECONDS -lt $FILEAGE ]; then
cp -r '$DIRCONT' $DEST >> /root/logs/${TODAY}archive2log
if [[ -f '/mnt/dataoffload/$CUSTOMER/$DIRCONT' ]]; then
echo "File $DIRCONT would have been removed" #For testing only
#rm --force $DIRCONT >> /root/logs/${`date +%D`}archive2log
fi
fi
done
echo "All files move to $2."
fi
And the results is:
cp: cannot stat '$DIRCONT': No such file or directory
Yet when I do an ls
command it is there, and more importantly, if I do the command cp -r <filelocation/filename> <destination/>
then it works fine. Further, if I issue a pwd
in the script, it shows it to be sitting in the correct directory, and the echo line returns the correct file/directory name(s) so I really don't see why it is not able to stat the file or directory.
I believe my problem most likely is in the line for loop line, but the output seems correct. Before I put the single quote around the ./
part, it seemed to work as long as there were no spaces in the file names; however, if there were spaces, it would parse out each word and try it as a separate file. The single quotes as shown returns everything properly, but none of it works, so I am not sure if this is progress or congress ;)
Can anyone explain why, or, (perhaps) more importantly tell me how to fix the code?