Customizing your Bash prompt to show the current Git branch name can make your coding life easier. When you work on different branches in Git, it’s helpful to see which branch you’re on directly in your terminal. This simple guide will show you how to add the Git branch name to your Bash prompt. You don’t need to be an expert; just follow the easy steps provided.
Show Git Branch Name in Bash Prompt
A Guide to Show Git Branch Names in Your Bash Prompt
Step 1: Open Your Terminal
First, you need to open your terminal. Make sure you are logged in with correct user to which you want to change bash prompt. This is where you will make the changes.
Step 2: Edit Your Bash Profile
You need to edit the .bashrc or .bash_profile file. This file controls how your terminal looks and behaves. To edit it, type the following command:
nano ~/.bashrc
If you are using macOS, you might need to edit .bash_profile instead:
nano ~/.bash_profile
Step 3: Add Git Branch Information
Now, you need to add a function to show the Git branch in your prompt. Scroll to the bottom of the file and add this code:
# Function to show the current Git branch
parse_git_branch() {
git branch 2> /dev/null | sed -e ‘/^[^*]/d’ -e ‘s/* (.*)/(1)/’
}
# Custom PS1 prompt
export PS1=”[33[1;36m]u[33[1;31m]@[33[1;34m]h:[33[1;35m][e[32m]w [e[91m]$(parse_git_branch)[e[00m]$ “
parse_git_branch(): This function finds the current Git branch.
PS1: This variable sets your prompt. It includes your username (u), hostname (h), current directory (w), and the Git branch ($(parse_git_branch)).
To save the file, press CTRL + X, then Y, and then ENTER.
Step 4: Apply the Changes
To apply the changes, you need to reload the file. Type:
source ~/.bashrc
Or, if you edited .bash_profile, type:
source ~/.bash_profile
Step 6: Test Your New Prompt
Now, navigate to a Git repository directory and you should see the Git branch name in your prompt.
cd /path/to/your/git/repository
Your prompt should now look something like this:
username@hostname /current/directory (branch-name) $
Conclusion
Customizing your Bash prompt to show the Git branch name can make your workflow more efficient. With this setup, you can always see which branch you are working on without typing extra commands.
The post How to Show Git Branch Names in Your Bash Prompt appeared first on TecAdmin.
Source: Read More