Profile picture
Sidharth R
  • Home
  • Posts
  • Journal
  • Home
  • Posts
  • Journal
  • Search

How to Set Git Username and Email Using Environment Variables

Updated: 12 Sep 2024 ⚬ Page views: 261

Introduction

Git associates a username and email with every commit. The username and email are retrieved from Git’s configuration, which can be set globally (for all repositories) or locally (for a specific repository). For example to set the username globally, you can run the command git config --global user.name "Your Name".

However, an alternative way to achieve this is by using environment variables. This can be useful for several reasons, such as:

  • Flexibility: You can easily change your Git username and email based on the project or system you’re working on.
  • Automation: Environment variables can be set automatically in different environments, like CI/CD pipelines, without needing manual configuration.
  • Quick setup: You don’t need to run Git commands every time—just set the environment variables once, and they apply automatically.
  • Separate identities: Easily switch between different identities for work, personal, or open-source projects.

Setting Git username and email via environment variables

Git checks for following environment variables and uses them during commits:

  • GIT_AUTHOR_NAME: specifies the author’s name for commits.
  • GIT_AUTHOR_EMAIL: specifies the author’s email for commits.
Note: When a commit is created in Git, it first checks for the username and email set by environment variables. If these variables are present, they are used. If not, the values from the Git configuration are used. This means environment variables take precedence over configuration.

Setting environment variables in Bash

If you’re using a Bash shell (common on Linux and macOS), you can set these variables like this:

export GIT_AUTHOR_NAME="Your Name"
export GIT_AUTHOR_EMAIL="your.email@example.com"

You can add these lines to your .bashrc or .bash_profile file to ensure they are set every time you open a terminal session.

Setting environment variables on Windows

On Windows, you can set environment variables via the command prompt or PowerShell:

Command Prompt:

setx GIT_AUTHOR_NAME "Your Name"
setx GIT_AUTHOR_EMAIL "your.email@example.com"

PowerShell:

$env:GIT_AUTHOR_NAME = "Your Name"
$env:GIT_AUTHOR_EMAIL = "your.email@example.com"

Conclusion

Setting Git username and email via environment variables offers flexibility, especially in automated or temporary environments. By using environment variables, you can configur Git quickly and consistently across different environments, making your workflow more efficient.


Reference

  • Git Internals - Environment Variables | Pro Git book

Nerdsid.com

Links
  • Home
  • Contact
  • About
  • Posts
  • Journal
  • Quotes
© 2025 Sidharth R.
All content on this website is licensed under CC BY-NC-SA 4.0.