Как я могу отобразить текущий путь ветки и папки в терминале?
Я смотрел несколько видеороликов Team Treehouse и у них очень красивый терминал при работе с Git.
Например, они имеют (что-то похожее):
[email protected]: [/Work/test - feature-branch-name] $ git add .
[email protected]: [/Work/test - feature-branch-name] $ git commit -m "Some feature."
[email protected]: [/Work/test - feature-branch-name] $ git checkout master
[email protected]: [/Work/test - master] $ git status
Как мой терминал может показать мне полезную информацию о том, в какой ветке я подключаюсь, с цветами, чтобы отличать биты данных, которые я хочу? Есть ли какой-то де-факто плагин, который я еще не нашел?
Я использую Mac OSX 10.8
Ответы
Ответ 1
Это не о плагине. Это о быстрых трюках в оболочке.
Для прохладной настройки в bash, проверьте проект dotfiles
этого парня:
https://github.com/mathiasbynens/dotfiles
Чтобы получить приглашение, введите .bash_prompt
в ~/.bash_profile
или ~/.bashrc
.
Чтобы получить то же самое приглашение, что и в вашем вопросе, измените строку export PS1
в конце .bash_prompt
следующим образом:
export PS1="\[${BOLD}${MAGENTA}\]\u\[$WHITE\]@\[$ORANGE\]\h\[$WHITE\]: [\[$GREEN\]\w\[$WHITE\]\$([[ -n \$(git branch 2> /dev/null) ]] && echo \" - \")\[$PURPLE\]\$(parse_git_branch)\[$WHITE\]] \$ \[$RESET\]"
В конце концов я использовал все .bash*
файлы из этого репозитория около месяца назад, и это было действительно полезно для меня.
Для Git в .gitconfig
есть дополнительные лакомства.
И поскольку вы являетесь пользователем Mac, в .osx
есть еще больше плюсов.
Ответ 2
Простой способ
Откройте ~/.bash_profile
в своем любимом редакторе и добавьте нижеследующее содержимое.
Git введите приглашение.
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1="\[email protected]\h \[\033[32m\]\w - \$(parse_git_branch)\[\033[00m\] $ "
ADD GIT НАИМЕНОВАНИЕ ФИЛИАЛА НА ТЕРМИНАЛ ПРОМПТ (MAC)
Ответ 3
Чтобы расширить существующие ответы, очень простой способ получить отличный терминал - использовать проект Dotfiles с открытым исходным кодом.
https://github.com/mathiasbynens/dotfiles
![enter image description here]()
Установка очень проста в OSX и Linux. Выполните следующую команду в терминале.
git clone https://github.com/mathiasbynens/dotfiles.git && cd dotfiles && source bootstrap.sh
Это будет:
- Git клонировать репо.
-
cd
в папку.
- Запустите установку bash script.
Ответ 4
Моя подсказка включает в себя:
- Выход из состояния последней команды (если не 0)
- Отличительные изменения при корне
-
rsync
-style [email protected]:pathname
к совершенству копирования и вставки - Git ветка, индекс, модифицированная, неотслеживаемая и восходящая информация
- Красивые цвета
Пример:
Чтобы сделать это, добавьте следующее в ваш ~/.bashrc
:
#
# Set the prompt #
#
# Select git info displayed, see /usr/share/git/completion/git-prompt.sh for more
export GIT_PS1_SHOWDIRTYSTATE=1 # '*'=unstaged, '+'=staged
export GIT_PS1_SHOWSTASHSTATE=1 # '$'=stashed
export GIT_PS1_SHOWUNTRACKEDFILES=1 # '%'=untracked
export GIT_PS1_SHOWUPSTREAM="verbose" # 'u='=no difference, 'u+1'=ahead by 1 commit
export GIT_PS1_STATESEPARATOR='' # No space between branch and index status
export GIT_PS1_DESCRIBE_STYLE="describe" # detached HEAD style:
# contains relative to newer annotated tag (v1.6.3.2~35)
# branch relative to newer tag or branch (master~4)
# describe relative to older annotated tag (v1.6.3.1-13-gdd42c2f)
# default exactly eatching tag
# Check if we support colours
__colour_enabled() {
local -i colors=$(tput colors 2>/dev/null)
[[ $? -eq 0 ]] && [[ $colors -gt 2 ]]
}
unset __colourise_prompt && __colour_enabled && __colourise_prompt=1
__set_bash_prompt()
{
local exit="$?" # Save the exit status of the last command
# PS1 is made from $PreGitPS1 + <git-status> + $PostGitPS1
local PreGitPS1="${debian_chroot:+($debian_chroot)}"
local PostGitPS1=""
if [[ $__colourise_prompt ]]; then
export GIT_PS1_SHOWCOLORHINTS=1
# Wrap the colour codes between \[ and \], so that
# bash counts the correct number of characters for line wrapping:
local Red='\[\e[0;31m\]'; local BRed='\[\e[1;31m\]'
local Gre='\[\e[0;32m\]'; local BGre='\[\e[1;32m\]'
local Yel='\[\e[0;33m\]'; local BYel='\[\e[1;33m\]'
local Blu='\[\e[0;34m\]'; local BBlu='\[\e[1;34m\]'
local Mag='\[\e[0;35m\]'; local BMag='\[\e[1;35m\]'
local Cya='\[\e[0;36m\]'; local BCya='\[\e[1;36m\]'
local Whi='\[\e[0;37m\]'; local BWhi='\[\e[1;37m\]'
local None='\[\e[0m\]' # Return to default colour
# No username and bright colour if root
if [[ ${EUID} == 0 ]]; then
PreGitPS1+="$BRed\h "
else
PreGitPS1+="$Red\[email protected]\h$None:"
fi
PreGitPS1+="$Blu\w$None"
else # No colour
# Sets prompt like: [email protected]:~/prj/sample_app
unset GIT_PS1_SHOWCOLORHINTS
PreGitPS1="${debian_chroot:+($debian_chroot)}\[email protected]\h:\w"
fi
# Now build the part after git status
# Highlight non-standard exit codes
if [[ $exit != 0 ]]; then
PostGitPS1="$Red[$exit]"
fi
# Change colour of prompt if root
if [[ ${EUID} == 0 ]]; then
PostGitPS1+="$BRed"'\$ '"$None"
else
PostGitPS1+="$Mag"'\$ '"$None"
fi
# Set PS1 from $PreGitPS1 + <git-status> + $PostGitPS1
__git_ps1 "$PreGitPS1" "$PostGitPS1" '(%s)'
# echo '$PS1='"$PS1" # debug
# defaut Linux Mint 17.2 user prompt:
# PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\[email protected]\h\[\033[01;34m\] \w\[\033[00m\] $(__git_ps1 "(%s)") \$ '
}
# This tells bash to reinterpret PS1 after every command, which we
# need because __git_ps1 will return different text and colors
PROMPT_COMMAND=__set_bash_prompt
Ответ 5
Пакет git, установленный в вашей системе, содержит bash файлы, которые помогут вам создать информационное приглашение. Чтобы создать цвета, вам нужно будет вставить строки вывода escape-последовательности в свою подсказку. И последний ингредиент должен обновить ваше приглашение после выполнения каждой команды с помощью встроенной переменной PROMPT_COMMAND.
Измените свой ~/.bashrc, чтобы включить следующее, и вы должны получить приглашение в своем вопросе, по модулю некоторые цветовые различия.
#
# Git provides a bash file to create an informative prompt. This is its standard
# location on Linux. On Mac, you should be able to find it under your Git
# installation. If you are unable to find the file, I have a copy of it on my GitHub.
#
# https://github.com/chadversary/home/blob/42cf697ba69d4d474ca74297cdf94186430f1384/.config/kiwi-profile/40-git-prompt.sh
#
source /usr/share/git/completion/git-prompt.sh
#
# Next, we need to define some terminal escape sequences for colors. For a fuller
# list of colors, and an example how to use them, see my bash color file on my GitHub
# and my coniguration for colored man pages.
#
# https://github.com/chadversary/home/blob/42cf697ba69d4d474ca74297cdf94186430f1384/.config/kiwi-profile/10-colors.sh
# https://github.com/chadversary/home/blob/42cf697ba69d4d474ca74297cdf94186430f1384/.config/kiwi-profile/40-less.sh
#
color_start='\e['
color_end='m'
color_reset='\e[0m'
color_bg_blue='44'
#
# To get a fancy git prompt, it not sufficient to set PS1. Instead, we set PROMPT_COMMAND,
# a built in Bash variable that gets evaluated before each render of the prompt.
#
export PROMPT_COMMAND="PS1=\"\${color_start}\${color_bg_blue}\${color_end}\[email protected]\h [\w\$(__git_ps1 \" - %s\")]\${color_reset}\n\$ \""
#
# If you find that the working directory that appears in the prompt is ofter too long,
# then trim it.
#
export PROMPT_DIRTRIM=3
Ответ 6
Просто установите плагины oh-my-zsh
как описано в этой ссылке.
![enter image description here]()
Лучше всего работает на MacOS и Linux.
Базовая установка
Oh My Zsh устанавливается путем запуска одной из следующих команд в вашем терминале. Вы можете установить это через командную строку с помощью curl
или wget
.
через завиток
sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"
через wget
sh -c "$(wget https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh -O -)"
Ответ 7
Существует много генераторов PS1, но ezprompt также имеет статус git (2-я вкладка "Элементы состояния").
Ответ 8
Основываясь на ответе 6LYTH3, я решил опубликовать свое собственное из-за некоторых улучшений, которые могут пригодиться:
Простое решение
Откройте ~/.bash_profile
и добавьте следующее содержимое
# \[\e[0m\] resets the color to default color
reset_color='\[\e[0m\]'
# \[\033[33m\] sets the color to yellow
path_color='\[\033[33m\]'
# \e[0;32m\ sets the color to green
git_clean_color='\[\e[0;32m\]'
# \e[0;31m\ sets the color to red
git_dirty_color='\[\e[0;31m\]'
# determines if the git branch you are on is clean or dirty
git_prompt ()
{
# Is this a git directory?
if ! git rev-parse --git-dir > /dev/null 2>&1; then
return 0
fi
# Grab working branch name
git_branch=$(git branch 2>/dev/null| sed -n '/^\*/s/^\* //p')
# Clean or dirty branch
if git diff --quiet 2>/dev/null >&2; then
git_color="${git_clean_color}"
else
git_color="${git_dirty_color}"
fi
echo " [$git_color$git_branch${reset_color}]"
}
export PS1="${path_color}\w\[\e[0m\]$(git_prompt)\n"
Это должно:
1) Prompt the path you're in, in color: path_color.
2) Tell you which branch are you.
3) Color the name of the branch based on the status of the branch with git_clean_color
for a clean work directory and git_dirty_color for a dirty one.
4) The brackets should stay in the default color you established in your computer.
5) Puts the prompt in the next line for readability.
Вы можете настроить цвета с этим списком
Изощренное решение
Другой вариант - использовать Git Bash Prompt, установить с этим. Я использовал опцию через Homebrew на Mac OS X.
git_prompt_list_themes
чтобы увидеть темы, но мне не понравилась ни одна из них.
git_prompt_color_samples
чтобы увидеть доступные цвета.
git_prompt_make_custom_theme [<Name of base theme>]
чтобы создать новую пользовательскую тему, необходимо создать файл .git-prompt-colors.sh.
subl ~/.git-prompt-colors.sh
чтобы открыть git-prompt-colors.sh и настроить:
Файл .git-prompt-colors.sh должен выглядеть так с моей настройкой
override_git_prompt_colors() {
GIT_PROMPT_THEME_NAME="Custom"
# Clean or dirty branch
if git diff --quiet 2>/dev/null >&2; then
GIT_PROMPT_BRANCH="${Green}"
else
GIT_PROMPT_BRANCH="${Red}"
fi
}
reload_git_prompt_colors "Custom"
Надеюсь, это поможет, хорошего дня!
Ответ 9
Пожалуйста, пройдите по этой ссылке.
https://gist.github.com/purnendu-roy/1ef4726483f95f3b1b29efb097423614
Ответ 10
Для тех, кто ищет, как это сделать в macOS Catalina (10.15), которая отказывается от bash в пользу zsh, вот мой файл .zshrc:
parse_git_branch() {
git branch 2> /dev/null | sed -n -e 's/^\* \(.*\)/[\1]/p'
}
COLOR_DEF=$'\e[0m'
COLOR_USR=$'\e[38;5;243m'
COLOR_DIR=$'\e[38;5;197m'
COLOR_GIT=$'\e[38;5;39m'
NEWLINE=$'\n'
setopt PROMPT_SUBST
export PROMPT='${COLOR_USR}%[email protected]%M ${COLOR_DIR}%d ${COLOR_GIT}$(parse_git_branch)${COLOR_DEF}${NEWLINE}%% '