Git diff Command – How to Compare Changes in Your Code
Hey friends, маєте ever been working in Git and found yourself wondering if you're going to stage the correct changes?
Або ти можеш відвідати те, що змінити ви будете брати участь в команді compared to ваш останній комітет. Perhaps you want to see the differences between two branches, commits, or files.
Вони є спільними проблемами і завданнями, коли працюють з версією системи управління. Fortunately, ви можете зробити все це за допомогою Git Diff Command.
I know you're probably concerned with your time, so let's get this ride on the road.
And don't worry – I will teach you each command with a fun example. Just start to read the article cheerfully.
git diff – the Universal diff Command
git diff lists out зміни between your current working directory and your staging area.
Let's таке як: I created a Git repository which is cat_vs_dog . No, це не formal repo, але це quite serious 😉. Then I created cat.txt і dog.txt .
They introduce themselves with their names – як це:
Там буде змінювати це зміна до штангової області за допомогою git add cat.txt dog.txt . Want to confirm? The use git status , які показують, які зміни є ready to commit like below:
Then, let's say I want to make some changes to the dog's name – як I wish to call it "pup" instead of "puppy".
Після того, як я ходьбу git diff command, it shows nothing. Can you guess why? Якщо ви не можете, що є повністю fine. Just continue to travel with me and pause on this for a few seconds.
Now, I changed "puppy" to "pup". Це cool to call it pup.
Prior to staging them, I wish to see that what I changed in my current working directory (that is the current working folder) compares with the staged changes.
To do this, I run the git diff command. Now you can see they differences below.
Це kinda makes sense, але це ще й мало weird, право? Не буде скинутий, Я можу, щоб ви хотіли, щоб всі line of diff's outcome.
Зовнішній, we ran the git diff command which shows nothing. Тому git diff показує відмінності між змінами у вашій робочій директорії і проміжної області. Але, будь-яка зміна будь-якого в робочій директорії після того, як змінити зміни. So, there is nothing different while compared with the staged area. I hope that makes sense.
Understanding git diff 's Results – Line by Line
Line 1 – It's 2 versions of the same file. Git named it A for the 1st version and B for the 2nd version.
Line 2 – Meta data про файл which is not super useful to your life. Перші два hashes надходять з двома файлами, що є compared. 100644 is an internal file mode identifier.
Line 3 – Git assigned a minus sign (-) to the A version of the file and a plus sign (+) to the B version of the file.
Line 4 – Git normally shows a chunk of lines що має бути встановлений, не написує файл.
- The line starting with the (-) символ came from the A version
- The line starting with the (+) символ came from the B version
За винятком змінених ліній, які також включають деякі лінії з коду до і після того, що почати до show the context.
Line 5 – Every chunk starts with a Chunk header. The chunk header will be identified by @@ (at the start and end). Then, there are two sets of numbers. Can you see the -1 and +1?
- -1 means from the A version file, extracting one line starting at line 1.
- +1 means from the B version file, extracting one line starting at line 1.
If the sets look like -3,4
+3,2, then:
- -3,4 means from A version file, extracting four lines starting from line 3.
- +3,2 means from B version file, extracting 2 lines starting from line 3.
No newline at the end of the file – Text texts that there no lines after those modified lines.Це означає, що, в наведеному прикладі, я призначила лише одну лінію і я змінила саму лінію. So, there are no more lines after that.
That's why it displays "No newline at end of file" in the diff's outcome. Hope you get my point.
Celebration time
Такий tiny second to celebrate ваш cognitive effort. Тому, що ви хотіли, щоб ваші hands dirty with diff's outcome. Now, you have strong foundation so you can start to learn more commands with a smile.
How to Compare Staged Changes in Git
Before you commit your changes, you can compare the staged changes with the last commit. Ви можете вказати на одну flag --staged or --cached . I love --staged because it makes sense. If you prefer --cached , that's good, too.
Let me explain it through an example. Вперше ми зробили наші змінилися зміни в нашій cat_vs_dog repo. Якщо ви не можете повідомити, що ми повторювали, вони встановлюються їм, як китти і puppy.
Вони будуть спричинені зміни – що є, ми будемо змінювати "пупп" до "пупу", який не скасовується.
Fine, first we commit the staged changes by git commit -m "intro to cat and dog" :
Now, stage the "puppy" to "pup" зміна. Then, run the git diff --staged command which lists out the changes між the staged area and your last commit.
- A version – Last Commit containing the line My name is puppy in dog.txt
- B version – staging area which differed from the last commit. Як "puppy" to "pup" in dog.txt .
Від того, як ми вивчаємо, ми скористалися тим, що ми робимо зміни і проміжок – "my name is puppy" з A version and "my name is pup" від B version.
I hope you're now able до compare зміни і recognize what we changed by looking at diff's outcome. diff is a super powerful command that lets you compare changes in lots of ways.
4 Diff Comparisons You Need to Know
Ви можете керувати git diff HEAD command to compare the both staged and unstaged changes with your last commit.
Ви можете також керувати git diff command to compare changes from the first branch with changes from the second branch. Order does matter when you're comparing branches. So diff's outcome will change depending on the order.
Top Tip: Порядок comparison розглядає коміти тільки. Це не здавалося б, щоб змінити і змінити зміни.
Ви можете керувати git diff the command to compare the changes between two commits. Як branch comparison, order does matter в comparing commits.
Ви можете run the below commands to compare the changes for specific file:
- git diff HEAD
- git diff
- git diff --staged or git diff --cached ,
- git diff
- git diff
Conclusion
I hope this article helps you make your next commit or staging more accurate. Your mindset is important when working with Git commands. Handle it with confidence and you can learn from any mistakes.
Якщо ви впевнені, що потрібно, щоб бути updated в цьому словнику, жити безкоштовно для ping me😜.
Якщо ви збираєтеся це far, тому що автор до show them you care. Say Thanks
Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started
freeCodeCamp є донор-підтриманим tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)
Наша місія: для людей, які беруть участь у коді для безкоштовного. Використовуйте це, створюючи тисячі відеозаписів, статей, і interactive coding lessons - всі доступні для громадськості.
Додатки до безкоштовногокодуКомп до нашої освіти ініціативи, і доступні плати для серверів, послуг, і staff.
Trending Books and Handbooks
- Learn CSS Transform
- Build a Static Blog
- Build an AI Chatbot
- What is Programming?
- Python Code Examples
- Open Source for Devs
- HTTP Networking in JS
- Write React Unit Tests
- Learn Algorithms в JS
- How to Write Clean Code
- Learn PHP
- Learn Java
- Learn Swift
- Learn Golang
- Learn Node.js
- Learn CSS Grid
- Learn Solidity
- Learn Express.js
- Learn JS Modules
- Learn Apache Kafka
- REST API Best Practices
- Front-End JS Development
- Learn to Build REST APIs
- Intermediate TS and React
- Command Line for Beginners
- Intro to Operating Systems
- Learn to Build GraphQL APIs
- OSS Security Best Practices
- Distributed Systems Patterns
- Software Architecture Patterns
Команда Git Diff. Як порівнювати зміни в Git
Для виведення змін у файлах порівняно з останнім коммітом використовується git diff без параметрів:
Команда виводить зміни до файлів, які ще не були додані до індексу. Порівняння відбувається з останнім комітом.
Порівняння з останнім комітом, включаючи файли в індексі
Якщо ви змінили якісь файли у вашому робочому каталозі і додали один або кілька з них в індекс (за допомогою git add), то команда git diff не покаже зміни цих файлів. Щоб показати зміни у файлах, включаючи файли, додані до індексу, використовується ключ --cached :
Порівняння коммітів
Команда git diff дозволяє порівнювати два різні коміти. Спочатку потрібно визначити хеш (ID) коммітів, які потрібно порівнювати. Можна скористатися командою git log, щоб вивести список коммітів та їх ідентифікатори:
Тепер порівняємо два коміти. Для цього як перший аргумент команді git diff вказується хеш першого комміта, а другим аргументом хеш другого комміта, наприклад:
git diff 4612297 5e356cf
Порівняння двох гілок
Для виведення всіх змін між кінцями двох гілок, необхідно для git diff вказати імена гілок:
git diff branch1 branch2
Порівняння файлів між двома гілками
Для порівняння конкретних файлів між двома гілками використовується команда:
git diff branch1 branch2 ./myfile.cpp
Замість branch1, branch2 потрібно вказати назву гілок, а натомість myfile.cpp шлях до порівнюваного файлу. Через пропуск можна додати ще файли для порівняння.
Виключити деякі файли з порівняння
Іноді потрібно виконати git diff, але виключити один або кілька файлів, щоб команда git diff їх проігнорувала. Для цього використовується запис виду ':(exclude)ім'я_файлу' або короткий запис ':!ім'я_файлу'
git diff -. ':(exclude)file1.abc' ':(exclude)file2.abc'
Або коротший запис:
git diff -. ':!file1.abc' ':!file2.abc'
Порівнювати лише зміни у файлах (ігнорувати нові та віддалені файли)
Щоб виключити з порівняння нові та видалені файли, можна скористатися опцією --diff-filter , яка дозволяє вибирати які саме зміни (файли) потрібно порівнювати.
Щоб порівняти тільки зміни всередині файлів (ігноруючи нові, видалені, перейменовані файли) використовується ключ Modified (M) — --diff-filter=M :
git diff --diff-filter=M
Дивіться також:
- Як змінити файли у старому коміті (не останньому)
- Як додати всі файли до комміту, крім одного
- Як створити гілку із попереднього комміту
- Команда Git stash. Як ховати зміни в Git
- Як показати файли, які будуть додані до поточного комітету
- Як змінити дату комітету
- Як встановити Git
- Як додати файли до останнього комітету
- Як створити новий репозиторій
- Як об'єднати коміти