This content originally appeared on DEV Community and was authored by Khalif AL Mahmud
As developers, we often want quick access to recent Git activity, especially when switching between projects. With a few simple adjustments to your shell’s configuration, you can have your terminal automatically display the latest Git commit message and hash each time you open it within a Git repository. In this tutorial, we’ll set up a function to show the last commit in both Zsh and Bash.
Step 1: Edit Your Shell Configuration File
Depending on your shell, you’ll need to edit either the .zshrc
(for Zsh) or .bashrc
(for Bash) file. Follow these steps:
- Open your shell configuration file:
nano ~/.zshrc # for Zsh users
nano ~/.bashrc # for Bash users
This will open the configuration file in your chosen text editor.
Step 2: Add a Function to Fetch the Last Commit
Next, add a custom function that will fetch and display the last commit message and hash from your Git history.
Copy and paste the following code snippet into your .zshrc
or .bashrc
file:
show_last_commit() {
if [ -d .git ]; then
echo "Last commit: $(git log -1 --pretty=format:'%h - %s (%cr)')"
fi
}
Step 3: Run the Function When Your Terminal Starts
To execute the function every time you open a new terminal session, add the following line at the end of your .zshrc
or .bashrc
file:
show_last_commit
This line will call the show_last_commit function each time you start a new terminal session, displaying the last commit if you’re in a Git repository.
Step 4: Apply the Changes
Once you’ve added the function and set it to run on startup, save and close the file. Then, source your configuration file to apply the changes immediately:
source ~/.zshrc # for Zsh users
source ~/.bashrc # for Bash users
Example Output
Now, when you navigate to a directory with Git initialized, you’ll see the last commit displayed automatically in your terminal:
Last commit: abc1234 - Fix layout issue on home page (3 hours ago)
If you’re not in a Git repository, the message won’t appear, keeping your prompt clean and relevant.
With just a few lines of code, you’ve now added a handy feature to your terminal! Not only does this display save you time, but it also keeps you informed about your project’s recent changes. Whether you’re using Zsh or Bash, this quick enhancement is a simple way to streamline your workflow.
Happy coding!
This content originally appeared on DEV Community and was authored by Khalif AL Mahmud
Khalif AL Mahmud | Sciencx (2024-10-27T04:15:20+00:00) Show the Last Commit of a GitHub Repository in Terminal Prompt. Retrieved from https://www.scien.cx/2024/10/27/show-the-last-commit-of-a-github-repository-in-terminal-prompt/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.