Define bash aliases to run git as specific user


Is it possible to define a function in a bash script which generically defines git-aliases for different users in order to let users apply their changes on a shared system so that the commits contains their username and email?

alias git_as_user1='GIT_AUTHOR_NAME="User1_pre User1_sur" GIT_AUTHOR_EMAIL="[email protected]" GIT_SSH="/home/account/" GIT_COMMITTER_NAME=$GIT_AUTHOR_NAME GIT_COMMITTER_EMAIL=$GIT_AUTHOR_EMAIL git'

I came up with the following function, but it does not evaluate args at the time of the alias definition but later on, when the alias is called.
This is unintended and renders the approach useless.

function alias_git_as ()
  alias git_as_$1='GIT_AUTHOR_NAME=$1 GIT_AUTHOR_EMAIL=$2

In .basrc:

alias_git_as "login" "Surname Prename" "[email protected]"

-> Won’t work !!! -> Defines the alias git_as_login, but the second and third arg are dismissed. When a certain user runs git_as_login from his terminal he would need to pass "Surname Prename" "[email protected]" again. But the args should be captured at time the alias is defined.


Two issues:

  • You use single quotes, but those suppress expansion; to make expansion happen early, you need double quotes instead.
  • Your original code only takes two arguments, but your example usage uses three.

Also, to make this work with names with spaces, we use the bash 5.x feature ${[email protected]} below.

# define the function
alias_git_as() { alias "git_as_$1=GIT_AUTHOR_NAME=${[email protected]} GIT_AUTHOR_EMAIL=${[email protected]}"; }

# use the function
alias_git_as "login" "Surname Prename" "[email protected]"

# use the invoked alias

See this working at

A version that’s compatible with older versions of bash while still retaining support for unusual author names may instead look like:

alias_git_as() {
  local alias_def
  printf -v alias_def 'git_as_%s=GIT_AUTHOR_NAME=%q GIT_AUTHOR_EMAIL=%q' "$1" "$2" "$3"
  alias "$alias_def"

Answered By – Charles Duffy

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published