Home > Software design >  bash: corrupted files after cp and mv commands
bash: corrupted files after cp and mv commands

Time:01-27

I'm watching a folder on my synology, using a scheduled bash script (the bash script is being executed every minute), where all scanned documents are being dropped. My idea is to move them to two places, one is the paperless-ng folder and an unsorted folder, so I can move them to the correct folder by hand.

#!/bin/bash
dpath=/volume1/scanned/*
for FILE in $dpath
do
if [[ -f $FILE ]]
then
    cp $FILE /volume1/unsorted_documents/
    mv $FILE /volume1/docker/paperless/consume/
else
    echo “There are no files in the given path.”
fi
done

This script ends up in documents being corrupt, most of the time. My thought is that it isn't finished copying before the move command is being executed.

Is there a way to make sure that the copy is done, before the move is being executed? Or another, better solution?

CodePudding user response:

I think your problem is related to dpath variable assignment. Try using find to get a list of files

#!/bin/bash
dpath=$(find /volume1/scanned -maxdepth 1 -type f)
# dpath=/volume1/scanned/*
for FILE in $dpath; do
  cp "$FILE" /volume1/unsorted_documents/
  mv "$FILE" /volume1/docker/paperless/consume/
done

CodePudding user response:

Thank you for all your answers! I took every answer in consideration and wrote another script, which should work much better. If there are any comments or recommendations, please let me know

# #!/bin/bash
destinationFolders=("/home/user/destination-1" "/home/user/destination-2")
scanFolder="/home/user/source"

function getFiles {
    readarray -d '' files < <(find $1 -maxdepth 1 -type f ! -name "*.proc" -print0)
}

function checkFileIsCopied {
    destinationFile=$(stat -c%s "$2")
    echo "$1 $destinationFile"
    while [ "$1" != "$destinationFile" ]
    do
        sleep 1
        destinationFile=$(stat -c%s "$2")
        echo "The file is still moving to $2 : $1 / $destinationFile"
    done
}

function renameFiles {
    files=$1
    renamedFiles=()
    for file in ${files[@]}; do
        mv "$file" "$file.proc"
        renamedFiles =("$file.proc")
    done
}

function moveFiles {
    local files
    local renamedFiles

    getFiles $1
    renameFiles $files

    for file in ${renamedFiles[@]}; do
        f="$(basename -- $file)"
        for destination in ${destinationFolders[@]}; do
            cp "$file" "$destination/$f" & checkFileIsCopied $(stat -c%s "$file") "$destination/$f"
            mv "$destination/$f" "$destination/${f%.*}"
        done
        rm "$file" 
    done
}

moveFiles $scanFolder
  •  Tags:  
  • Related