Advanced Git: Power Commands Beyond the Basics (r) (r)

Jun 21, 2023
Little figures standing around learning all about advanced git

Share this on

Git is a powerful program to manage version control, and holds some sort of monopoly this area. In most everyday tasks, Git can be simple to operate due to the repetition of commands. But, there are plenty of situations where you need more than the basics. As such, there are many advanced Git commands that can enhance your Git abilities to a higher stage.

It will also expose you to various Git concepts you might not typically encounter. Examples include stashing files instead of committing changes, rebasing, and putting files in the staging area. Once you learn the techniques, you could discover that you can add even more impact on your team.

In this blog, introduce different command options you need to learn. To use them, you need some skills, concepts, and information available. We'll look at this in the beginning.

Briefly, here's a quick list of aspects that you need to know:

  • Core Git concepts like commits, branches, pull requests, and many more.
  • Familiarity with basic Git commands like the git add, git merge, git commit, and git push.

It's beneficial to know how working using Git in a team setting, since certain commands may have a significant impact on an open source codebase. For instance, it could be the case that you use the commands you're using in a position of responsibility. This means you need to be aware and gain a clear understanding what you are doing when you are using these commands.

Advanced Git 12 Power Commands That You'll Need to Learn

This piece will discuss 12 advanced Git commands that can take your Git skills to the next level and make you an expert Git wizard. Let's start with a option you could prefer to use over others.

1. Rebasing

Rebasing, for starters, is an effective Git command that's alternative to a pull request. It lets you pull all of the new commits you make after a branch divergence into an entirely new branch. It then slots the changes at the tip of your base. This can be helpful if you wish to include changes from another branch, without having to create an merge commit, for any reason.

A common reason for rebasing is when you're working on a feature branch, and you want to incorporate changes from the main branch, without having to create the merge commit. This helps keep your history in order, however it may take longer to complete as well as you might encounter higher number of errors when merging.

To rebase a branch, use the git rebase command. Here's an example of changing the base of one branch to another:

 git checkout foo-branch
git rebase main

It is also possible to list the commits you're going to publish and provide you with an opportunity to alter the commits prior to release. In this way, you'll be able to squash commits, edit commit messages and much more. You can use this flag along with the interactive or --i flag to perform an  interactive rebase.'

 Rebase git --interactive "other-branch-name> 

Speaking of which, squashing commits into one to clear up the commit history is a common use case for rebasing. This will make your commit history easier to comprehend and read.

In order to do this in a rebase, you adhere to the flag that indicates the number of commits that you'd want to eliminate, and makes the commits one.

 Git rebase -i HEAD3
 

The button will bring up the rebase window interactively as the commit window. In this window you are able to edit and choose the commits you wish to remove:

A partial Terminal window showing the output from a git rebase command. The screen shows three commits, alongside hash IDs and the ‘pick’ command. Underneath, there is a list of commands to help create a custom rebase.
A git rebase is running inside the Terminal.

There is a set of commits listed on the top of your screen. There's a selection of commands on the bottom with some other relevant details. It is the default choice to choose a commit, which will select it as the one that you wish to utilize and does not make any modifications.

But, there are many different commands that can help you get through the rebase process. For instance, you can reword a commit or combine multiple commits. For making changes, and using the commands, you'll be using the terminal's editor. Most often, it's Vim. This means that you must know the editor.

The final step is to backup your modifications, and later push them onto the branch that is remote.

2. Reverting, Resetting, and unstaging

Git is notorious when it comes to reversing modifications. This is a challenging process all around, with a penchant to throw errors. However, if you make changes to your working directory or staging area which you wish to reverse you can use a couple of Git commands that could assist.

In actual fact, Git provides instructions on how to unstage an entire file in the event that you have an Git status:

A Terminal window showing the user running a git status command. The output shows the current branch and the changes to be committed. There’s also instructions to unstage a file.
Git showing you how to remove a file when it is in the status output.

So, you are able to take a commit out of the current branch and send the same commit to another branch with ease.

git reset HEAD 
 

It's like shifting your branch back by one commit. This is similar to when you were removing the most recent commit. You might even have a use case that requires you to reset a branch to its previous status. Here, you can reset it against the remote origin by using the git reset command --hard origin/main as an example. However, note that any changes made will be gone forever.

Although the checkout command is a one that you will use often and is considered basic, you can also use it to unstage files before making a change:

git checkout -- 
 

Note the space between the dashes and the filename placeholder. The command destages the specific file, and deletes any modifications in the directory that you are working on. Be aware that this deletes any local changes you make to the file. Therefore make sure to double- and triple-check that you do not need the unsalved changes.

It is also possible to use Git revert to roll back modifications you create to commit. This isn't a way to roll back your modifications, but instead creates a brand new commit based on undoing the modifications made in the prior one.

The main difference is that this command will not move any reference pointers to the new commit but retains the old commits. This is helpful for when you need to reverse the changes but not remove them from your commit history.

The command is expecting to get reference from the command that it can easily change the commit that was made:

git revert HEAD

However, you have much more options to restore and change files and commits. The two subsequent entries on this list of more advanced Git commands will look at these commands.

3. Restoring files to default States

With Git, you can easily return a file back to its previous state with the relatively new command Git restore. It is recommended to consider this a replacement for reset in git generally speaking because it gives you an additional level of power under the underneath the. In particular, you could get the same result using git restore --staged for filename> similar to what you get with git reset.

The command can do more, though - you're also able to restore files to default states. The way to accomplish this by execute the command git statustoo:

Git restore the filename

The changes will be removed from the working directory, as if nothing had taken place. As with the git checkout command"filename> You must ensure you don't want any local changes since they'll disappear forever.

4. Modifying Commitments

There's a good chance that there will be plenty occasions when you press a commit and then realize you did not include something important. When using Git it's easy to modify the commit in order to incorporate the missing changes.

This is accomplished by following a specific process:

  • First, make your changes in the files that you require to complete the project.
  • Create them in a typical way with the git add.
  • Recommit those changes in the staging area using another command for the commit:
git commit --amend
 

This amends the original commit with the new one using your staging area for it. Therefore, ensure that you do not require the older version of the file as it will be lost. We also recommend you use the --amend option for local commits, rather than remote ones for the same reasons as we cover in the rest of this article.

It is also possible to make use of the commit command git commit --amend to alter the message of commit only using these commands:

 commit to git --amend -m "New committed message"
 

5. Git Logging

The Git log can be useful for helping to understand the history of a repository. However, we wouldn't class the log command as an advanced. Instead, you can utilize several options to limit the output according to your requirements:

git log
 
 git log --decorate
 
 git log --stat
 

For example, decorating a log entry prints out ref names of all commits that are displayed. The --stat option displays insertions and deletions in a given commit

A Terminal window showing the output of a git log --stat command. It shows two commits, with the hash highlighted in gold, the author, date of commit, the commit message, and both the number of files changed and inserted.
Executing a git log –stat command from the Terminal.

Additionally, you can use different methods to alter the output of the log - called 'commit limiting. In this case follow these commands:

git log --author=
 
 git log --grep=
 

In this section, you can filter the log using specific authors' names or patterns of text. You can combine several options and flags to generate an account for a particular goal. As an example, consider this command:

git log --oneline --author= --since= feature-temp
 

This searches for all commits with the feature-temp branch from a singular writer since a specific date. Then, it prints it out using one line of entries. Note that the parameter may include a number:

 --since="Two weeks ago"
 --since="Two weeks ago"

Additionally, if you would like to search a specific file instead of a branch, then you could use:

 Log git -- oneline --author=bartonfink --since="5 days ago" -- readme.rm
 

The examples in this set is only a glimpse of what you could do using your logs. However, there's plenty of scope to locate exact commits inside these logs, based on the requirements for search.

6. Git Hooks

There is a good chance that you are using macros and other automated scripts in order to execute code in a specific order. Git also includes this type of functionality in the form of hooks. These scripts automatically run in response to certain events like commits or pushes. There are many methods to make use of hooks to enforce code formatting as well as run tests and much more.

There are two types of hooks: client-side and server-side:

  • Client-side hooks trigger based on local actions like merges and commits.
  • Server-side hooks will trigger because of network operation. It can happen when a repo receives an unpushed commit, for example. numerous other instances.

Git is always able to fill your repo with a variety of examples of hooks when you execute an git init. But, you must remove the .sample extension in order to use them:

A Finder window in macOS showing the hidden hooks folder for a Git repo. It contains a host of sample hook script files, each with a .sample extension.
A folder within macOS that contains the samples of hooks Git installs upon the first.

It is important to note that you are able to only use one kind of hook at any one time, although it is possible to run multiple scripts at the same time with a little effort. So, your files names should correspond to the type of hook that you'd prefer to run in accordance with the examples of programs: pre-commit, update, and so on.

Making a Git Hook

In order to create a Git hook, will need to write an executable script in the .git/hookssubdirectory without an extension. It will still run when you include hooks to your hooks folder.

#!/usr/bin/env Python

In this way, you are able to create your code in the normal way. In this case, for instance, there's a prepare-commit script written in Python that prompts the user to write excellent commit messages

#!/usr/bin/env python
 
 import sys, os
 
 path_commit_msg = sys.argv[1]
 
 with open(commit_msg_filepath, 'w') as f:
 
 f.write("# You'll need to provide a better commit message than that, buddy!")

Though it's rarely necessary, we'd recommend you run the command chmod +x .git/hooks/ in the command line to ensure you are able to execute the command.

Overall hooks are an effective tool to automate routine tasks, and for ensuring the good practices in your group.

7. Commit Referrals

bc7623b7a94ed3d8feaffaf7580df3eca4f5f5ca
 

Instead, Git provides several ways to name commits in short, memorable names. You could, for instance, use a branch or tag name. For example, consider a branch called "develop". Here's an example in which we're referring to the most recent commit on this branch:

git diff develop..HEAD
 

The following table shows the difference between the most recent version ( HEAD) to the "develop" branch as well as the latest commit.

It is also possible to refer to a commit based on its location within history of the commit. As an example, you might refer to two commits before this one with the HEAD~2 abbreviation:

git diff HEAD~2..HEAD
 

Git additionally offers several other ways to refer to commits, such as making use of"@" to refer to the current branch, or using "@" symbol to indicate the branch currently in use or the "*" symbol to indicate the parent commit. With these shorthand terms it is possible to save time and avoid mistakes in working on commits.

8. Stashing

Under normal scenarios, you'd believe there is no way to store changes you make to files without committing them. "Stashing" is one way to do this temporarily. It's a great option when you have to move branches around or perform a specific task but don't want to commit your changes yet.

For instance, if you need to switch branches to tackle something mid-flow, you can store the changes on the current branch, and then checkout the other. Once you have that, you are able to do the same thing on the second branch, and then commit and push those changes. Then, you can checkout and retrieve your work on the original branch.

For storing changes, there are two ways to accomplish this:

git stash
 

The changes are stored in a different stash and reverts your working directory back to the previous HEAD commit (the condition it was in before making new changes). You can list your modifications with the git stash listing and then examine the contents of your stash with the git stash display. The latter command can also accept any format git diff will accept.

In this way, you are able to change branches, or focus on a different task. If you wish to restore your work, use the following procedure:

Git stash apply

This will apply the last stored changes to the working directory. However, note that you can still encounter conflicts if you change the file too much. After all, git stash provides a temporary solution for your issue.

It is also possible to have several stashes, and you can choose which one to use by following the steps:

the git stash application [email protected]In

The placeholder is a placeholder that uses an integer in turn, [email protected][email protected] indicates the current stash. The official Git documentation provides additional examples of git stash.

9. Bisecting

Simply put, the command locates bugs via a search of the commits you have made. Once it finds the offending commit, it will return it to you. The power of this command includes all the subcommands that you are able to use.

For bisecting to work, you first have to execute the Git bisect begin command. Git will then take you to the initial commit in your project's history.

Here, you will need to indicate whether that commit is good or bad by using the appropriate commands:

git bisect good
 
 git bisect bad
 

The Git system will take you on to the next commit, for a test of its "quality.' Note that you can also replace "good" by "old" as well as bad with "new" to match the specific needs of your application (although it is not possible to mix the terms.)

In this way, you are able to continue to mark each commit as positive or negative until you discover the one that introduced the bug. However, you don't have to trawl through every commit. You can simply use specific identifiers to narrow down and shorten the search.

git bisect bad feature-test
 

In this case, it is using an identifier for a branch. However, this could refer to a specific revision that uses an integer, a hash reference, and more. Whatever the case, once you have searched and find the bug, you can run either of the following commands to bring back your current version of code:

git bisect reset
 

Similar to all advanced Git commands on this list, there's much more to digest in reading the Git documentation will be a crucial read here.

10. Comparing Branch

Our article on commit references talks about using git diff. It's now time to study this process further. It is common to find yourself in multiple branches which contain various revisions. Git allows you to compare differences between two branches using the "git diff" command. You can use it in a number different ways, usually in conjunction with other commands to examine and analyse a repo.

The fundamental git diff command will give you output with an overview of the modifications. It looks a lot like the output of a commit merging investigation.

A portion of the Terminal window that shows a typical git diff output. It shows the files being compared, the index refs, the key and legend for changes between the documents, and the actual changes themselves.
Displaying the output of a git diff request.

But, it is possible to drill down to exact branches, hashes and so on. For instance, to examine two branches, run the branch1..branch2 command. branch1..branch2 command, and replace the placeholders:

git diff feature-branch pre-prod
 

Also, you can compare different aspects between the branch you are currently in with a different branch:

git diff HEAD..pre-prod
 

It is important to note that two dots in this case will show an amount that is different between two tips of the branches. In contrast, three dots will reveal the distinction between the two branch's common ancestor. utilize that data to evaluate.

Like similar to git log You can also clean out the output and then improve the information it provides. For instance, git diff --name-only branch1..branch2 will only check the files that differ, and leaves the rest of the information:

A portion of a Terminal window that shows how to run a git diff --name-only command. It returns a list of file names only, as per the command.
The git diff command from the Terminal.

It is possible that the output can be difficult to understand particularly if the "diff' is lengthy. If this happens, you can use the color-words option.

A Terminal window showing the lengthy output of a git diff request, complete with color references for words. It shows which files are being compared, explicit references to changes and deletion between files, and the changes themselves from the files. Each has color coding to help differentiate them from the rest of the text.
Running the git diff -color-words command and viewing the results in Terminal.

Overall, git diff can be just as powerful than other commands, and especially in the case of some options and fine-tune the changes you report.

11. Application of Individual Commitments

In some cases, you might want to apply a specific commit from a branch to another without merging the two branches. Git permits this with the cherry-pick feature of git. You should use this carefully, but you can find that the git cherry-pick will help in a few scenarios.

There are times when there are feature branches that have been stale that you haven't merged into main or trunk. You could use a combination of commands (such as the git log) to search old relevant commits out and apply them to other branches.

You can use git log to determine the reference of a commit. Then, ensure you're on the branch you'd like to cherry pick for a reference. As an example, let's say you're looking to pick the commit that contains the number xxxxxaaaaaaaaaaaa into"the branch " trunk". Check your branch first...

Git checkout trunk

...then pick your commitments:

git cherry-pick xxxxxaaaaaa
 

Your commit message will likely have been out of date at times. For this reason it is possible to pass your --edit option into the command. It will allow you to provide a new commit message before the cherry selection.

12. Supercharging "git add"

To conclude our discussion of the latest Git power option will be a look at the the git add. No, that's not a typo - this fundamental Git command has some surprising power under its hood.

In the case of instance, if you're able to find yourself adding your own documents to the staging area, you could make use of the following methods:

Add git -p

The -p option lets you make the changes in an interactive manner. It allows you to review changes you've made to every file and then decide which ones to stage. This can save you a lot of time and help you avoid creating a change that you don't want to make.

You may have heard that it is possible to stage specific file, you are able to specify a directory too. For example, to create a stage for all files in the " new-feature" directory:

Add new feature to git

It is possible to test what the result of the commit to git is without running the process fully. There is a choice for this:

git add --dry-run
 
 git add -n
 

If you execute this command, Git will show you whether it will add or remove the files. In the case of files that are ignored it is also possible to add them to the staging area if you want to:

Add --force to git
to git, then add -f

The process of adding files to the staging area could be more difficult than just a binary "Add or do not make" scenario. As such, one of Git's most core commands is able to handle a variety of scenarios.

Summary

After you've got the basics of Git commands within your pockets You have 80% of what is required to carry out the standard version control tasks. However, the final 20 percent is where advanced Git commands are able to shine.

Techniques and commands like the rebasing process, bisecting technique, restoration of documents, and so on will help you get from a jam quickly. Additionally, you could offer greater value to your team as well as your project. You can help to streamline workflows improve productivity and have an all-around greater effect as a programmer.

Will any of these advanced Git commands be part of your daily routine? Please let us know in the comment section below!