I need to create a code that will:
- Check for two arguments at the start minus the script name itself (i.e
dar /mnt/sdb1 /root/testdir/testarc
with$1 = /mnt/sdb1
and$2 = /root/testdir/testarc)
- Copy all files with a
.doc
,.pdf
and.PDF
file extension from the source directorysdb1
(and its sub directories) to the destination directory - Use some type of
cmp
command (or perhapsdiff
?) to rename any files that may have the same name but different data during the copy process - If there is a
.PDF/.pdf
file with the same data as a.doc
file then the.PDF/.pdf
file should not be copied, only the.doc
version
So far I have managed 1 and 2. 3 and 4 have me stumped.
Ignore the for
loop, it's useless.
Here's my source code:
#!/bin/bash
sourcePath=$1
destPath=$2
Filedoc="*.doc"
Filepdf="*.pdf"
FilePDF="*.PDF"
if [[ $# -ne 2 ]]; then
echo "Usage ; dar doc_path archive_path"
exit 1
fi
if [ ! -d sourcePath ]
then echo Directory does not exist
fi
if [ ! -d destPath ]
then mkdir -p $destPath
fi
for file in $(find "${sourcePath}" -type f -exec basename {} \; | sort | uniq -d); do
num=1
fileName=$(echo "${file}" | cut -d '.' -f1)
fileExtension=$(echo "${file}" | cut -d '.' -f2)
dirName=$(dirname "${duplicate}")
for duplicate in $(find "${sourcePath}" -name "${file}" | tail -n +2 ); do
mv "${duplicate}" "${duplicate}${fileName}_${num}.${fileExtension}"
echo "Renamed duplicate file ${duplicate} ${duplicate}_${num}.${fileExtension}"
(( num = num + 1 ))
done
done
for file in $(find "${sourcePath}" -name "*.pdf"); do
fileName=$(echo "${file}" | cut -d '.' -f1)
if $(find $(sourcePath) -name "${fileName}.doc" &>/dev/nulll; then
echo "Sorry, a .doc file with that extension already exists, skipping copy"
continue
fi
done
find "${sourcePath}" -name "$Filedoc" -exec cp -r {} "${destPath}" \;
find "${sourcePath}" -name "$Filepdf" -exec cp -r {} "${destPath}" \;
find "${sourcePath}" -name "$FilePDF" -exec cp -r {} "${destPath}" \;
diff
(manual page here man7.org/linux/man-pages/man1/diff.1.html) The 4th point however is somewhat quite more complex than just a simple Bash script can do. Doc files and PDF files are binaries, but in different formats, therefore, from a binary point of view they are always going to be different-iname
instead of-name
in the find commands to reduce the number of searches. And you can combine both in the same find command. But if the names can differ you risk having to diff a large number of files. Finally the variables used in your sample code are inconsistent.