1

I happen need to use the following shell script

find . -type f -exec sh -c '
mv "$0" "${0%/*}/$(printf "%s\n" "${0##*/}" | sha1sum | cut -d" " -f1)"
' {} \;

But I do not understand how does this script work? For instance, how to analyze

mv "$0" "${0%/*}/$(printf "%s\n" "${0##*/}" | sha1sum | cut -d" " -f1)"
' {} \;

piece by piece? Thanks.

1 Answer 1

2
printf "%s\n" "${0##*/}"

${0##*/} takes the path $0 and strips off any leading directory names, leaving only the file name. The printf command adds a newline to the end and then this file name is piped to...

| sha1sum | cut -d" " -f1

This computes the SHA-1 hash of the file name and then uses cut to extract just the hash from sha1sum's output.

${0%/*}

This is the opposite of ${0##*/}—this one gets the directories from $0 and throws away the file name.

So effectively, what ends up getting run is:

mv "$DIR/$FILENAME" "$DIR/$HASH_OF_FILENAME"

In English, it renames every file it finds to the SHA-1 hash of the original file name.


For what it's worth, it could be simplified a bit and made more readable. I might write the mv command as:

mv "$0" "$(dirname "$0")/$(basename "$0" | sha1sum | awk "{print \$1}")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.