Skip to content

Instantly share code, notes, and snippets.

@matiaskorhonen
Last active November 11, 2020 16:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matiaskorhonen/fc5d03b02dc09b36e8d62ab891402994 to your computer and use it in GitHub Desktop.
Save matiaskorhonen/fc5d03b02dc09b36e8d62ab891402994 to your computer and use it in GitHub Desktop.
Generate SHA256 recursively in a directory tree. Uses the same checksum file format as https://linux.die.net/man/1/sha256sum
#!/usr/bin/env ruby
require "digest"
require "find"
require "optparse"
options = {}
OptionParser.new do |opts|
opts.banner = "Usage: recursive-hashes [options]"
opts.on("-c", "--check DIR", "Check hashes") do |c|
options[:check] = c
end
opts.on("-g", "--generate DIR", "Generate SHA256SUMS files") do |v|
options[:generate] = v
end
opts.on("-h", "--help", "Prints this help") do
puts opts
exit
end
end.parse!
puts options.inspect
if options[:generate]
Find.find(options[:generate]) do |path|
if FileTest.directory?(path)
if File.basename(path)[0] == "."
Find.prune
# Don't look any further into this directory
else
files = Dir.glob(File.expand_path("*.*", path)).reject { |f| File.directory?(f) }
if files.any?
puts "#{files.size} file(s) in #{path}"
hashes = files.map do |file|
sha256 = Digest::SHA256.file(file)
[sha256.hexdigest, File.basename(file)].join(" ")
end
digest_file = File.expand_path("SHA256SUMS", path)
File.open(digest_file, "w+") do |f|
f.write hashes.join("\n")
f.write "\n"
end
puts " -> created SHA256SUMS"
end
next
end
end
end
end
@slavanap
Copy link

#!/bin/bash
shopt -s globstar
sha256sum ./** > ../sums.txt

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment