0
0
Gitdevops~5 mins

SHA-1 hashing concept in Git - Commands & Configuration

Choose your learning style9 modes available
Introduction
SHA-1 hashing creates a unique code for data to identify it easily. It helps Git track changes and find files quickly without storing duplicates.
When you want to check the unique ID of a file or commit in Git.
When Git needs to verify if a file has changed or stayed the same.
When you want to see the commit history with unique commit IDs.
When you want to share a specific commit by its unique SHA-1 hash.
When Git stores objects like commits, trees, and blobs using SHA-1 hashes.
Commands
This command creates a new Git repository named 'my-repo' to start tracking files and changes.
Terminal
git init my-repo
Expected OutputExpected
Initialized empty Git repository in /home/user/my-repo/.git/
Change directory into the new repository to work inside it.
Terminal
cd my-repo
Expected OutputExpected
No output (command runs silently)
Create a new file named 'file.txt' with the text 'Hello Git' to add to the repository.
Terminal
echo "Hello Git" > file.txt
Expected OutputExpected
No output (command runs silently)
Stage the new file so Git knows to include it in the next commit.
Terminal
git add file.txt
Expected OutputExpected
No output (command runs silently)
Create a commit that saves the current state of the repository with a message describing the change.
Terminal
git commit -m "Add file.txt with greeting"
Expected OutputExpected
[main (root-commit) 1a2b3c4] Add file.txt with greeting 1 file changed, 1 insertion(+) create mode 100644 file.txt
-m - Adds a commit message inline without opening an editor
Show the commit history with short SHA-1 hashes and commit messages to identify commits quickly.
Terminal
git log --oneline
Expected OutputExpected
1a2b3c4 Add file.txt with greeting
--oneline - Displays each commit in a single line with short SHA-1 hash
Calculate and show the full SHA-1 hash of the file content to see its unique identifier in Git.
Terminal
git hash-object file.txt
Expected OutputExpected
3b18e7a2a1f4c9d5e6f7a8b9c0d1e2f3a4b5c6d7
Key Concept

If you remember nothing else from this pattern, remember: Git uses SHA-1 hashes to uniquely identify and track every file and commit.

Common Mistakes
Trying to use SHA-1 hashes without committing files first
No commits or objects exist yet, so Git cannot show hashes for them
Add and commit files before checking their SHA-1 hashes
Confusing full SHA-1 hashes with short hashes shown in logs
Short hashes are abbreviations and may not be unique in large repos
Use full SHA-1 hashes when exact identification is needed
Summary
Initialize a Git repository to start tracking files.
Add and commit files to create objects identified by SHA-1 hashes.
Use git log and git hash-object to view SHA-1 hashes for commits and files.