Bash – Generate MD5sum for all files in a directory, and then write (filename).md5 for each file containing that file’s MD5SUM

bashhashsum

I have a directory full of files. Each file will be copied to a specific type of destination host.

I want to calculate an MD5 sum for each file in the directory, and store that md5 sum in a file that matches the name of the file that generated the sum, but with .md5 appended.

So, for instance, if I have a directory with:

a.bin
b.bin
c.bin

The final result should be:

a.bin
a.bin.md5     # a.bin's calculated checksum
b.bin
b.bin.md5     # b.bin's calculated checksum
c.bin
c.bin.md5     # c.bin's calculated checksum

I have attempted this with find exec, and with xargs.

With find, I tried this command:

find . -type f -exec md5sum {} + > {}.md5

Using xargs, I tried this command:

find . -type f | xargs -I {} md5sum {} > {}.md5

In either case, I end up with a file called {}.txt, which isn't really what I am looking for.

Could anyone point out how to tweak these to generate the md5 files I am looking to generate?

Best Answer

cd /path/to/files &&
for file in *; do
    if [[ -f "$file" ]]; then
        md5sum -- "$file" > "${file}.md5"
    fi
done
Related Question