Show current branch on terminal

大憨熊 提交于 2021-01-29 04:52:01

问题


Is there any way to show in Terminal of VS Code to show in brackets current branch? I saw it somewhere but not sure how it can be done. By some extension or whatever..

C:/myUser/project> git status

I would like to see it something like:

C:/myUser/project>(master) git status

回答1:


For Linux Terminal

You can modify the PS1 variable. PS1 is a Bash Environment Variable that represents the primary prompt string which is displayed when the shell is ready. You can achieve your result by modifying this variable with a script. First, get the output of your current value of the variable by running

$ echo $PS1

Sample output:[\u@\h \W]$

Now you save the following code in a bash file(Remember to replace the initial string of export PS1 with the output of the above command).

#!/bin/bash
source ~/.bashrc
get_cur_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
 }
export PS1="[\u@\h \W]\$(get_cur_branch)\$ "

Let's say path of the file is "/home/samar/Documents/my_vs_script.sh"

Now change your VS code settings by adding the following lines in 'settings.json'

"terminal.integrated.shellArgs.linux": [
"--init-file",
"/home/samar/Documents/my_vs_script.sh"
]

Now each time you open a new terminal in VS code, script file "my_vs_script.sh" will execute and you get the desired output.

For Windows-Powershell

The solution above works well for the Linux terminal. But if you want to do it for another command-line shell-like Powershell, you can change the 'setting.json' to

{
"terminal.integrated.shellArgs.windows": [
    "-NoExit",
    "-Command", "c:/scripts/myscript.ps1"
  ]
}

where 'myscript.ps1' must have a function 'prompt' definition to add git branch to your prompt.

You can refer this question for your 'myscript.ps1' code. You don't need to change 'Microsoft.PowerShell_profile.ps1'. Defining it in another file works too.

I hope it helps.




回答2:


Open zshrc file open ~/.zshrc

Add this text in the end of zshrc file

autoload -Uz vcs_info

precmd() { vcs_info }

zstyle ':vcs_info:git:*' formats 'on branch %b'

setopt PROMPT_SUBST

PROMPT='%n in ${PWD/#$HOME/~} ${vcs_info_msg_0_} > '

Source zshrc file source ~/.zshrc



来源:https://stackoverflow.com/questions/62514097/show-current-branch-on-terminal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!