简体   繁体   English

在终端中显示 git 用户名的 Bash 脚本

[英]Bash script to show git username in terminal

Does anyone know how to show git username in the terminal?有谁知道如何在终端中显示git username

I am using the following bash script for the branch, but, since I have several accounts I would like to show as well username or user email我正在为分支使用以下 bash 脚本,但是,由于我有多个帐户,因此我还想显示usernameuser email

BTW, I know I can use git config --global --list .顺便说一句,我知道我可以使用git config --global --list The idea is to see the info in the terminal without having to check every time, as with the branch这个想法是在终端中查看信息而不必每次都检查,就像branch

parse_git_branch() {
  git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}

export PS1="\u@\h \W\[\033[32m\]\$(parse_git_branch)\[\033[00m\] $ "

You can use git config --get to get a single configuration value, like the username.您可以使用git config --get获取单个配置值,例如用户名。 Then, you can wrap it in a function:然后,您可以将其包装在一个函数中:

parse_git_user() {
    git config --get user.email
}

And then you can incorporate it into the prompt ( PS1 ) in any format you wish.然后您可以将它以您希望的任何格式合并到提示 ( PS1 ) 中。 Eg:例如:

export PS1="\u@\h \W\[\033[32m\]\$(parse_git_branch)\[\033[00m\] ($(parse_git_user))$ "
# Here -----------------------------------------------------------^

I suspect you want to make sure you get the correct user.email for each of your projects?我怀疑您想确保为每个项目获得正确的user.email @Mureinik eloquently answered the question, but I think this may help you or someone else searching. @Mureinik 雄辩地回答了这个问题,但我认为这可能会帮助您或其他人进行搜索。

Rather than have the user.name in your prompt, I suggest you set it based on the remote url.我建议您根据远程 url 进行设置,而不是在提示中包含user.name That way it should just work™.这样它应该可以正常工作™。 It works by using a zsh hook every time you change into a directory.每次更改到目录时,它都会使用 zsh 钩子来工作。

autoload -Uz add-zsh-hook
set-git-email() {
  if [ -d .git ]; then
    remote=`git remote -v | awk '/\(push\)$/ {print $2}'`
    if [[ $remote == git@git.server.com:* ]]; then
       git config user.email user@email.com
    fi   
  fi
}
add-zsh-hook chpwd set-git-email
set-git-email

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM