Git Aliases

Gepostet von Luca am 24.01.2023

git aliases bash

Git aliases are a powerful way of customising the Git experience and increasing work performance. Looking at Git docs might make you think that using them is extremely complicated, but it really isn’t. First of all, we need to access the Git configuration file. All you have to do is input the following code:

git config --global --edit

Always remember that we need to use --global to access our aliases in any project. To edit our configuration file with a terminal instead, we can also open it in an external editor:

    editor = code --wait

code is for Visual Studio Code. As is the case with [core], we can implement the aliases simply by adding [alias] Now, assuming I would like to reach a specific line of a specific file in a remote branch, in my case I would need to know the current database version. To do that, I can of course look into the specific branch’s devops portal or fetch the branches, check out the target one, look at the line, and so on. But if I would like to take a more efficient approach to my work, I’d prefer to use three tricks I have up my sleeve. Sometimes, it is worth remembering that all Git commands aren’t always that easy. Mistakes might include the likes of incorrect arguments, forgotten arguments, typos and so on. For our example, we need to execute the following lines:

git fetch
git log -n <number of commits, 1 for the last one> -L<start line>,<end line or number of lines>:<target file> <revision-range>

This isn’t too hard to remember, but it might seem a bit silly each time you write out these commands properly. All you have to do is implement this command as an alias:

    db-version = "!f() { git fetch; git log -n 1 -L36,+4:MyProject/Database.cs origin/develop; }; f"

To know which <revision-range> to use, it can be useful to fetch remote branches – git fetch then git branch -a – and take remote/origin/HEAD -> origin/develop Close the config file, then call git db-version. This gives the following result:

@@ -36,4 +36,4 @@
         /// <summary>
         /// The database version
         /// </summary>
-        public static readonly Version DatabaseVersion = new Version(1, 54, 0);
+        public static readonly Version DatabaseVersion = new Version(1, 54, 1);

Of course, Git aliases also include arguments.
Imagine that we’d like to create and check out a new branch. We would need to pass the branch name to our alias command as shown below:

new-branch = "!f() { git checkout -b $1 }; f" --edit 

$1 is our argument and can also be used as feature/$1 or feature/ticket_$1

You can also use shell scripts and functions, more arguments, conditional statements, declaration variables and more besides. Take a look at Git docs. Have fun!