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/ssh_user_wrapper.sh" 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.
CodePudding user response:
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 ${var@Q}
below.
# define the function
alias_git_as() { alias "git_as_$1=GIT_AUTHOR_NAME=${2@Q} GIT_AUTHOR_EMAIL=${3@Q}"; }
# use the function
alias_git_as "login" "Surname Prename" "[email protected]"
# use the invoked alias
git_as_login
See this working at https://ideone.com/PV09NG
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"
}