简体   繁体   English

在 docker 容器中的 bash 命令提示符上添加 git 分支名称

[英]Add git branch name on bash command prompt in docker container

In my local bash, I could add git branch name on the bash command prompt by adding below code in ~/.bashrc在我的本地 bash 中,我可以通过在 ~/.bashrc 中添加以下代码在 bash 命令提示符上添加 git 分支名称

parse_git_branch() {
     git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1="\u@\h \[\033[32m\]\w\[\033[33m\]\$(parse_git_branch)\[\033[00m\] $ "

I add the same code to docker container ~/.bashrc when making docker image.在制作 docker 图像时,我将相同的代码添加到 docker 容器 ~/.bashrc 中。 However, it only colored the current directory but not showing branch name like below但是,它只为当前目录着色,但不显示如下分支名称

user@server /workspace/mydir ()

what I expect was like below.我所期望的如下所示。 The yellow bracket indicates which branch that I'm using.黄色括号表示我正在使用哪个分支。

user@server /workspace/mydir (master)

This is how I had to do in my Dockerfile where <<USERNAME>> should be replaced with the user that your docker is run as:这就是我在 Dockerfile 中必须执行的操作,其中<<USERNAME>>应替换为您的 docker 运行为的用户:

### Setup git branch view in CLI ############
RUN echo "parse_git_branch() {" >> /home/<<USERNAME>>/.bashrc \
    && echo "    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\\\1)/'" >> /home/<<USERNAME>>/.bashrc \
    && echo "}" >> /home/<<USERNAME>>/.bashrc \
    && echo "export PS1='\u@\h \[\033[32m\]\w\[\033[33m\]\$(parse_git_branch)\[\033[00m\] $ '" >> /home/<<USERNAME>>/.basic

The part that took me so long to figure this out is the three backslashes needed before the 1 in the grep of the sed command.我花了很长时间才弄清楚这一点的部分是 sed 命令的 grep 中的 1 之前需要的三个反斜杠。

My troubleshooting consisted of my looking at my.bashrc file inside of my Docker instance.我的故障排除包括查看我的 Docker 实例中的 my.bashrc 文件。 That is where I saw that the (\1) was being replaced with just () .那就是我看到(\1)被替换为()的地方。 So, if you're having this issue and my fix doesn't work for you, check your.bashrc file to see what it did do.因此,如果您遇到此问题并且我的修复对您不起作用,请检查您的 .bashrc 文件以查看它做了什么。

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

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