Skip to content

Instantly share code, notes, and snippets.

@slimlime
Last active March 19, 2022 19:33
Show Gist options
  • Save slimlime/c4907d98dbe8b834cb9f4f7bb7f39dcd to your computer and use it in GitHub Desktop.
Save slimlime/c4907d98dbe8b834cb9f4f7bb7f39dcd to your computer and use it in GitHub Desktop.
dotfiles
# Share ssh session between terminals see sock tok
env=~/.ssh/agent.env
agent_load_env () { test -f "$env" && . "$env" >| /dev/null ; }
agent_start () {
(umask 077; ssh-agent >| "$env")
. "$env" >| /dev/null ; }
agent_load_env
# agent_run_state: 0=agent running w/ key; 1=agent w/o key; 2= agent not running
agent_run_state=$(ssh-add -l >| /dev/null 2>&1; echo $?)
if [ ! "$SSH_AUTH_SOCK" ] || [ $agent_run_state = 2 ]; then
agent_start
ssh-add
elif [ "$SSH_AUTH_SOCK" ] && [ $agent_run_state = 1 ]; then
ssh-add
fi
unset env
# Depends on our environment defaults.
# Colour prompt check based on WSL2 Ubuntu LTS 20.04
# Add helpers for custom contextualised terminal prompt
# Add Git Bash-style branch meta context information to terminal prompt prefix
# See default coloured when working in VS Code remote terminals
# export PS1="\[\e]0;\u@\h: \w\a\]${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$"
# Gets the asterisked current branch name from git branch output using sed... Parenthesised output
show_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}
# Default comments and boilerplate that came with installation below:
# uncomment for a colored prompt, if the terminal has the capability; turned
# off by default to not distract the user: the focus in a terminal window
# should be on the output of commands, not on the prompt
#force_color_prompt=yes
if [ -n "$force_color_prompt" ]; then
if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
# We have color support; assume it's compliant with Ecma-48
# (ISO/IEC-6429). (Lack of such support is extremely rare, and such
# a case would tend to support setf rather than setaf.)
color_prompt=yes
else
color_prompt=
fi
fi
# Include the show_git_branch calls here
# WARNING: Differences in behaviour compared to the backslash-escaped dollar signs in StackOverflow sample.
# See non-escaped evaluated command and then the escape dollar sign when used as pure text literal.
# Works in VS Code
if [ "$color_prompt" = yes ]; then
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\] \[\033[31m\]$(show_git_branch)\[\033[00m\]\$ '
else
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w $(show_git_branch)\$ '
fi
unset color_prompt force_color_prompt
# Source helpers
~/bash-my-source/git-completion.bash
# Aliases
alias untar='tar -zxvf -v'
alias wget='wget -c -v '
alias getpass="openssl rand -base64 20"
alias sha='shasum -a 256 '
# alias ping='ping -c 5'
alias www='python -m SimpleHTTPServer 8000'
alias speed='speedtest-cli --server 2406 --simple'
alias ipe='curl --verbose ipinfo.io/ip'
# Git Bash Git\etc\profile.d\aliases.sh bug still loads these even with .bashrc present -----
# Some good standards, which are not used if the user
# creates his/her own .bashrc/.bash_profile
# --show-control-chars: help showing Korean or accented characters
# Aliases
alias l='ls -aF --color=auto --show-control-chars'
alias ls='ls -F --color=auto --show-control-chars'
alias ll='ls -lah'
alias ..='cd ..'
alias ...='cd ../..'
alias ....='cd ../../..'
## Other helpers
### Gzip-enabled `curl`
alias gurl='curl --compressed'
### Open duplicate git bash window in same pwd
alias git-bash='/git-bash.exe & > /dev/null 2&>1'
## Git
# Potential updated next versions of git with respective completion
# Use the file from here
# `curl https://raw.githubusercontent.com/git/git/v2.25.1/contrib/completion/git-completion.bash -o ~/.git-completion_v2.25.1.bash`
source ~/.git-completion_v2.25.1.bash
# Use global g main for all instead of per command. Simplicity.
# Hacky workaround which works for all the g-prefixed aliases g b g c g switch gsw
# for branch name autocompletion
__git_complete g __git_main
alias gs='git status -sb'
alias gd='git diff --staged -w --color-moved --color-moved-ws=ignore-all-space'
alias gc='git commit -am'
alias gf='git fetch --prune'
alias gp='git pull -a'
alias gpu='git push --follow-tags'
__git_complete gpu _git_push # Bash alias compatibility with git-completion # didn't work? gpu -u origin <autocompletebranch>
alias gsw='git switch'
__git_complete gsw _git_switch # Bash alias compatibility with git-completion
# Bash alias compatibility workaround for git-completion autocompletion
__git_complete gsw _git_switch # Compatibility with git-completion. Hacky private
alias ga='git add . --all'
alias gr='git rev-parse --show-toplevel' # git root
alias glt="git log --no-walk --tags --pretty=format:' %C(yellow)%h %Cgreen%d %Cred%ad %Creset%s' --date=local"
alias glbr='git log --oneline --decorate --graph --all'
alias gl='git log --oneline --decorate --graph -n 7'
# See diff back by number. otherwise default back by 1.
gitLookBack() {
# Expect happy input. Single digit $1 first arg.
git diff --staged -w --color-moved --color-moved-ws=ignore-all-space HEAD~$1
}
alias gdn='gitLookBack'
# See recent branches contextual information recent commit dates
alias gbrd='git branch --format='"'"'%(HEAD) %(color:yellow)%(refname:short)%(color:reset) - %(contents:subject) %(color:green)(%(committerdate:relative)) [%(authorname)]'"'"' --sort=-committerdate'
# See all the things all refs including stash in time context. i.e. WIP and branches
alias glstash='git log --date-order --all $(git reflog show --format="%h" stash)'
# Prefer the majority use case shorthand first. oneline first. Rather than appending 'o'
alias glall='git log --oneline --graph --decorate --all $(git reflog show --format="%h" stash) -n 10'
alias glallf='git log --graph --decorate --all $(git reflog show --format="%h" stash) -n 2'
## Tmux
alias tmux='tmux -2'
alias tmuxls="ls $TMPDIR/tmux*/"
tping() {
for p in $(tmux list-windows -F "#{pane_id}"); do
tmux send-keys -t $p Enter
done
}
tpingping() {
[ $# -ne 1 ] && return
while true; do
echo -n '.'
tmux send-keys -t $1 ' '
sleep 10
done
}
# npm winpty for Windows cmd
case "$TERM" in
xterm*)
# The following programs are known to require a Win32 Console
# for interactive usage, therefore let's launch them through winpty
# when run inside `mintty`.
for name in node ipython php php5 psql python2.7
do
case "$(type -p "$name".exe 2>/dev/null)" in
''|/usr/bin/*) continue;;
esac
alias $name="winpty $name.exe"
done
;;
esac
# _Git Bash Git\etc\profile.d\aliases.sh bug still loads these even with .bashrc present ----
# Fix gpg unable to sign commit data
export GPG_TTY=$(tty)
# Provide passphrase only once instead of getting multiple prompts each command/shell
# First: sudo apt install keychain
# add your key file name
eval `keychain --quiet --eval --agents ssh id_ed25519`
# Auto append commands to history workaround?
# PROMPT_COMMAND='history -a'
# Testing this history persistence
HISTSIZE=9000
HISTFILESIZE=$HISTSIZE
HISTCONTROL=ignorespace:ignoredups
_bash_history_sync() {
builtin history -a #1
HISTFILESIZE=$HISTSIZE #2
builtin history -c #3
builtin history -r #4
}
history() { #5
_bash_history_sync
builtin history "$@"
}
PROMPT_COMMAND=_bash_history_sync
default-cache-ttl 86400
max-cache-ttl 86400
New setup
# For the moment. Until refine with docker and devcontainers as well
echo 'Take as a guide rather than a script.'
Install nvm or fnm or volta ...
Linux or WSL2
Using the anonymous noreply email linked to GitHub in these examples
`30815731+slimlime@users.noreply.github.com`
# SSH and GPG with GitHub
ssh-keygen -t ed25519 -C "30815731+slimlime@users.noreply.github.com" # Copy out ~/.ssh/id_ed25519.pub for GitHub
# gpg vs gpg2? or already silently ported alias..
gpg --gen-key
gpg --list-secret-keys --keyid-format LONG # Get the key id here. Maybe a script can return most recent line
gpg --armor --export YOUR_KEY_ID # Get this public pgp key block for GitHub
# Set this up to only provide SSH passphrase the first time in Linux / WSL2 rather than per command or per shell.
# .bashrc: eval `keychain --quiet --eval --agents ssh id_rsa`
sudo apt install keychain
git config --global user.email 30815731+slimlime@users.noreply.github.com
git config --global user.name slinu
git config --global push.followTags true
git config --global commit.gpgsign true
git config --global user.signingkey
git config --global alias.co checkout
git config --global alias.c commit
git config --global alias.s status
git config --global alias.b branch
; - TODO: Test out the send up conflicts, refine to see alternatives later
; Recommended for performance and compatibility with future AutoHotkey releases.
#NoEnv
; Enable warnings to assist with detecting common errors.
; #Warn
; Some rough parts like Windows overrides.
; Lots of to dos to test after validating the value of the current ruleset.
; Nice work with the semicolon-as-modifier key though some workarounds
; Somep arts are dependent on your standard keyboard layout
; SendMode Input Recommended for new scripts due to its superior speed and reliability.
SendMode Input
; Ensure a consistent starting directory.
SetWorkingDir %A_ScriptDir%
; Use Caps Lock as a modifier only
SetCapsLockState AlwaysOff
#CapsLock::CapsLock
; Walk delete backwards forwards. Backslash (Delete backwards) slightly closer for piano fingers.
; Though kills common shortcuts remapped, conceptually, human big brain mental model
; For 10x dev vs 0.5x standard keyboard layout
; \::Backspace
; Backspace::Delete
CapsLock & \::\
; ??? Not working?? .... without, ctrl unpresses held down ';'
`; & ~Ctrl up::Send, {Ctrl Up}
; disable ctrl + ';' shortcut in google docs
; ~Ctrl & `;::Send, {Ctrl}
; Personal preference for one-handed colon character press usage
; ~^ & `;::;
LCtrl & `;::;
; CapsLock & `;::; ; This may be a trap?
; This appears to be the real one that allows CAPS + ; to send ;
`; & ~CapsLock up::Send, {CapsLock Up}
`; & j::Left
`; & i::Up
`; & k::Down
`; & l::Right
`; & h::Home
`; & o::End
`; & u::PgUp
`; & n::PgDn
; CapsLock & k::Media_Play_Pause
; CapsLock & j::Send {Ctrl down}{Alt down}{Shift down}{F6}{Ctrl up}{Alt up}{Shift up}
; CapsLock & l::Send {Ctrl down}{Alt down}{Shift down}{F7}{Ctrl up}{Alt up}{Shift up}
; CapsLock & h::Media_Prev
; CapsLock & o::Media_Next
; CapsLock & p::Media_Stop
; CapsLock & u::Send {Ctrl down}{Alt down}{Shift down}{F4}{Ctrl up}{Alt up}{Shift up}
; CapsLock & n::Send {Ctrl down}{Alt down}{Shift down}{F5}{Ctrl up}{Alt up}{Shift up}
Ctrl & q::Send !{F4}
; Interesting next line
CapsLock & Enter::
Send, {End}
Sleep, 2
Send, {Enter}
return
+WheelDown::WheelRight
+WheelUp::WheelLeft
@slimlime
Copy link
Author

slimlime commented Jun 9, 2021

Depending on version
i.e. 2.25.1 in latest ubuntu LTS

@slimlime
Copy link
Author

slimlime commented Jun 9, 2021

copypasta if need historical review

# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples

# If not running interactively, don't do anything
case $- in
    *i*) ;;
      *) return;;
esac

# don't put duplicate lines or lines starting with space in the history.
# See bash(1) for more options
HISTCONTROL=ignoreboth

# append to the history file, don't overwrite it
shopt -s histappend

# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)
HISTSIZE=1000
HISTFILESIZE=2000

# check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS.
shopt -s checkwinsize

# If set, the pattern "**" used in a pathname expansion context will
# match all files and zero or more directories and subdirectories.
#shopt -s globstar

# make less more friendly for non-text input files, see lesspipe(1)
[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"

# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then
    debian_chroot=$(cat /etc/debian_chroot)
fi

# set a fancy prompt (non-color, unless we know we "want" color)
case "$TERM" in
    xterm-color|*-256color) color_prompt=yes;;
esac

# uncomment for a colored prompt, if the terminal has the capability; turned
# off by default to not distract the user: the focus in a terminal window
# should be on the output of commands, not on the prompt
#force_color_prompt=yes

if [ -n "$force_color_prompt" ]; then
    if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
	# We have color support; assume it's compliant with Ecma-48
	# (ISO/IEC-6429). (Lack of such support is extremely rare, and such
	# a case would tend to support setf rather than setaf.)
	color_prompt=yes
    else
	color_prompt=
    fi
fi

if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
unset color_prompt force_color_prompt

# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
    PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
    ;;
*)
    ;;
esac

# enable color support of ls and also add handy aliases
if [ -x /usr/bin/dircolors ]; then
    test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)"
    alias ls='ls --color=auto'
    #alias dir='dir --color=auto'
    #alias vdir='vdir --color=auto'

    alias grep='grep --color=auto'
    alias fgrep='fgrep --color=auto'
    alias egrep='egrep --color=auto'
fi

# colored GCC warnings and errors
#export GCC_COLORS='error=01;31:warning=01;35:note=01;36:caret=01;32:locus=01:quote=01'

# some more ls aliases
alias ll='ls -alF'
alias la='ls -A'
alias l='ls -CF'

# Add an "alert" alias for long running commands.  Use like so:
#   sleep 10; alert
alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'

# Alias definitions.
# You may want to put all your additions into a separate file like
# ~/.bash_aliases, instead of adding them here directly.
# See /usr/share/doc/bash-doc/examples in the bash-doc package.

if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

# enable programmable completion features (you don't need to enable
# this, if it's already enabled in /etc/bash.bashrc and /etc/profile
# sources /etc/bash.bashrc).
if ! shopt -oq posix; then
  if [ -f /usr/share/bash-completion/bash_completion ]; then
    . /usr/share/bash-completion/bash_completion
  elif [ -f /etc/bash_completion ]; then
    . /etc/bash_completion
  fi
fi

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion




# Custom additions 20210609

# Aliases
alias untar='tar -zxvf -v'
alias wget='wget -c -v '
alias getpass="openssl rand -base64 20"
alias sha='shasum -a 256 '



# --show-control-chars: help showing Korean or accented characters

# Aliases
alias l='ls -aF --color=auto --show-control-chars'
alias ls='ls -F --color=auto --show-control-chars'
alias ll='ls -lah'

alias ..='cd ..'
alias ...='cd ../..'
alias ....='cd ../../..'

## Other helpers

### Gzip-enabled `curl`
alias gurl='curl --compressed'

### Open duplicate git bash window in same pwd
alias git-bash='/git-bash.exe & > /dev/null 2&>1'

## Git

# Potential updated next versions of git with respective completion
# Use the file from here
# `curl https://raw.githubusercontent.com/git/git/v2.25.1/contrib/completion/git-completion.bash -o ~/.git-completion_v2.25.1.bash`
source ~/.git-completion_v2.25.1.bash

# Allow git completion to work for bash aliases
__git_complete g __git_main

alias gs='git status -sb'
alias gd='git diff --staged -w --color-moved --color-moved-ws=ignore-all-space'
alias gc='git commit -am'
alias gf='git fetch --prune'
alias gp='git pull -a'
alias gpu='git push --follow-tags'
alias gsw='git switch'
__git_complete gsw _git_switch # Bash alias compatibility with git-completion

alias ga='git add . --all'
alias gr='git rev-parse --show-toplevel' 		# git root
alias glt="git log --no-walk --tags --pretty=format:' %C(yellow)%h %Cgreen%d  %Cred%ad  %Creset%s' --date=local"
alias glbr='git log --oneline --decorate --graph --all'
alias gl='git log --oneline --decorate --graph -n 7'


## Tmux
alias tmux='tmux -2'
alias tmuxls="ls $TMPDIR/tmux*/"
tping() {
  for p in $(tmux list-windows -F "#{pane_id}"); do
    tmux send-keys -t $p Enter
  done
}
tpingping() {
  [ $# -ne 1 ] && return
  while true; do
    echo -n '.'
    tmux send-keys -t $1 ' '
    sleep 10
  done
}

# Fix gpg unable to sign commit data
export GPG_TTY=$(tty)




@slimlime
Copy link
Author

slimlime commented Jun 9, 2021

WSL2 cat ~/.bashrc | clip.exe

@webstoreportal
Copy link

webstoreportal commented Jun 18, 2021

where to put

# -n count can be overridden by adding another -n arg at the end. So these serve as defaults to avoid blotting out whole terminals
# Contextualise all the work, including WIP stashes.
git log --date-order --all $(git reflog show --format="%h" stash)
git log --graph --decorate --all $(git reflog show --format="%h" stash) -n 2
git log --oneline --graph --decorate --all $(git reflog show --format="%h" stash) -n 10

# i.e.
git log -n10 -n1
+ git config --global alias.rl reflog
- l
# `git rl show stash` # is a decent way to list all the past stash for apply (don't pop!🎉🎈📌) # auto oneliners

Do GUIs provide any additional value over standard git aliased commands? - maybe for some esoteric ad hoc customisation that takes a while to type out / autocomplete


Some other parts to sort out, purge, merge or keep

alias gc='git commit -v -am' # using this less now, though it can be tedious with conflicts while using linting hooks on partial hunks partial stages
alias gd='git diff --staged -w --color-moved' # alias gd='git diff --staged -w --color-moved --color-moved-ws=ignore-all-space' # the zebra diff and whitespace ignore heuristics seem to clash sometimes
alias nr='npm run' # lol. doesnt save much in the way of key jumps already in natural position 

## Git stash preview git stash show -p 0 1 2 3 4  or stash@{0} or commit ref 
alias gsp='git stash show -p'

alias gtls='git tag -l --sort=-v:refname'
alias glp='git log --pretty=format:"%h %s" --graph' # better formats can improve on this... fuller, custom %ad vs %cd, relative


---

Maybe some portable terminal colours and default contextual symbols, timestamps, numbers, git info etc
 - need to make sure not to step on any non-portable parts, though, like zsh vs bash vs oh-my-zsh updates
 - 

@webstoreportal
Copy link

note ahk "forked" from @seant1

@slimlime
Copy link
Author

add gpg-agent.conf for caching passphrase when using gpgsign by default

@slimlime
Copy link
Author

add gpu to the autocompletions private binding

i.e. For the git push -u
set upstream origin commands to autocomplete long branch names

@slimlime
Copy link
Author

gpu -u origin <branchname>
autocomplete didn't work?

@slimlime
Copy link
Author

alias glall='git log --oneline --graph --decorate --all $(git reflog show --format="%h" stash) -n 10'
alias glallf='git log --graph --decorate --all $(git reflog show --format="%h" stash) -n 2'

Prefer the majority shorthand use case of seeing everything onelined first glall

Use extra letter
inverses some other convention that prefers the full input in the base command and appending a o to flag the oneliner.


Wonder if the extra git reflog stash hashes command is required when using git log -all (all refs)...

@slimlime
Copy link
Author

git log all only shows topmost stash WIP commit?? ∴ use reflog to get all the stash commits to contextualise in time order

@slimlime
Copy link
Author

slimlime commented Jun 27, 2021

GitKraken never replied to their spam marketing "asking for feedback" email when I spent time asking them to provide benefits >_>

Mass marketing mail spam that says they reply within one business day.... nekminit two weeks later

Update -- they never replied after follow-ups^

@slimlime
Copy link
Author

https://stackoverflow.com/questions/42209027/show-current-branch-and-coloring-on-linux-like-git-bash-on-windows

see defaults in bashrc

# make less more friendly for non-text input files, see lesspipe(1)
[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"

# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then
    debian_chroot=$(cat /etc/debian_chroot)
fi

# set a fancy prompt (non-color, unless we know we "want" color)
case "$TERM" in
    xterm-color|*-256color) color_prompt=yes;;
esac

# uncomment for a colored prompt, if the terminal has the capability; turned
# off by default to not distract the user: the focus in a terminal window
# should be on the output of commands, not on the prompt
#force_color_prompt=yes

if [ -n "$force_color_prompt" ]; then
    if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
        # We have color support; assume it's compliant with Ecma-48
        # (ISO/IEC-6429). (Lack of such support is extremely rare, and such
        # a case would tend to support setf rather than setaf.)
        color_prompt=yes
    else
        color_prompt=
    fi
fi

if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
unset color_prompt force_color_prompt

add git branch sed expression function to extract the asterisked current branch

(How does git bash get the GIT_DIR! warning though? This would not seem to replicate as git branch only gets the current branch text and the git branch command does not show a warning * isntead)

replace parts in the if colour condition (we want coloured terminal prompts) to also include a coloured and a non-coloured

@slimlime
Copy link
Author

e.g. StackOverflow https://stackoverflow.com/a/65418758

I am using Ubuntu 20.04 and the default PS1 is found under if [ "$color_prompt" = yes ]; then in the ~/.bashrc file.

Steps:

  1. Open the ~/.bashrc file and find if [ "$color_prompt" = yes ]; then
  2. Define the following bash function (Thanks @nogoseke) above the if statement (You can define it anywhere above the PS1 value in the file).
#show git branch
show_git_branch() {
   git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}
  1. Update the PS1 values to the following:
if [ "$color_prompt" = yes ]; then
    PS1="${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\] \[\033[31m\]\$(show_git_branch)\[\033[00m\]$ "
else
    PS1="${debian_chroot:+($debian_chroot)}\u@\h:\w \$(show_git_branch)\$ "
fi

The entire thing should look something like this:

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

if [ "$color_prompt" = yes ]; then
    PS1="${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\] \[\033[31m\]\$(show_git_branch)\[\033[00m\]$ "
else
    PS1="${debian_chroot:+($debian_chroot)}\u@\h:\w \$(show_git_branch)\$ "
fi
  1. Save the changes and restart your terminal.

@slimlime
Copy link
Author

For the command codes escape sequences

see \u \h \W

 When  executing  interactively,  bash displays the primary
   prompt PS1 when it is ready to read  a  command,  and  the
   secondary  prompt PS2 when it needs more input to complete
   a command.  Bash allows these prompt strings  to  be  cus­
   tomized by inserting a number of backslash-escaped special
   characters that are decoded as follows:
          \a     an ASCII bell character (07)
          \d     the date  in  "Weekday  Month  Date"  format
                 (e.g., "Tue May 26")
          \e     an ASCII escape character (033)
          \h     the hostname up to the first `.'
          \H     the hostname
          \j     the  number of jobs currently managed by the
                 shell
          \l     the basename of the shell's terminal  device
                 name
          \n     newline
          \r     carriage return
          \s     the  name  of  the shell, the basename of $0
                 (the portion following the final slash)
          \t     the current time in 24-hour HH:MM:SS format
          \T     the current time in 12-hour HH:MM:SS format
          \@     the current time in 12-hour am/pm format
          \u     the username of the current user
          \v     the version of bash (e.g., 2.00)
          \V     the release of bash,  version  +  patchlevel
                 (e.g., 2.00.0)
          \w     the current working directory
          \W     the  basename  of the current working direc­
                 tory
          \!     the history number of this command
          \#     the command number of this command
          \$     if the effective UID is 0, a #, otherwise  a
                 $
          \nnn   the  character  corresponding  to  the octal
                 number nnn
          \\     a backslash
          \[     begin a sequence of non-printing characters,
                 which could be used to embed a terminal con­
                 trol sequence into the prompt

@slimlime
Copy link
Author

slimlime commented Jul 21, 2021

Previous default

# uncomment for a colored prompt, if the terminal has the capability; turned
# off by default to not distract the user: the focus in a terminal window
# should be on the output of commands, not on the prompt
#force_color_prompt=yes

if [ -n "$force_color_prompt" ]; then
    if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
        # We have color support; assume it's compliant with Ecma-48
        # (ISO/IEC-6429). (Lack of such support is extremely rare, and such
        # a case would tend to support setf rather than setaf.)
        color_prompt=yes
    else
        color_prompt=
    fi
fi

if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
unset color_prompt force_color_prompt

Adjusted to include current git branch

# Add helpers for custom contextualised terminal prompt


# Add Git Bash-style branch meta context information to terminal prompt prefix
# export PS1="\[\e]0;\u@\h: \w\a\]${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$"
# Gets the asterisked current branch from git branch output using sed... Parenthesised output
show_git_branch() {
   git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}


# uncomment for a colored prompt, if the terminal has the capability; turned
# off by default to not distract the user: the focus in a terminal window
# should be on the output of commands, not on the prompt
#force_color_prompt=yes

if [ -n "$force_color_prompt" ]; then
    if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
        # We have color support; assume it's compliant with Ecma-48
        # (ISO/IEC-6429). (Lack of such support is extremely rare, and such
        # a case would tend to support setf rather than setaf.)
        color_prompt=yes
    else
        color_prompt=
    fi
fi

if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\] \[\033[31m\]\$(show_git_branch)\[\033[00m\]\$ '
else
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w \$(show_git_branch)\$ '
fi
unset color_prompt force_color_prompt

Note the addition of [\033[31m\]\$(show_git_branch)\[\033[00m\] $(show_git_branch)

I think the answer had a typo in not escaping the dollar sign for the coloured prompt string at the end?

@slimlime
Copy link
Author

Wow strange multiple answers either have typos in their dollar sign and escape codes or the different environment is evaluating differently

No escape for dollar sign for evaluation of expression here in both lines

if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\] \[\033[31m\]$(show_git_branch)\[\033[00m\]\$ '
else
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w $(show_git_branch)\$ '
fi

This works^
The function was working in terminal before the change; however, it was showing the literal string of "$(show_git_branch)" rather than evaluating it - fixed after removing the escape character... Not sure if this will lead to bugs in other uses as multiple answers copypasta'd with "$(show_git_branch)"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment