Search code examples
gitawkzsh

Not getting full branch name on mac(m1) terminal


Code:

# Find and set branch name var if in git repository.
function git_branch_name()
{
  branch=$(git symbolic-ref HEAD 2> /dev/null | awk 'BEGIN{FS="/"} {print $NF}')
  if [[ $branch == "" ]];
  then
    :
  else
    echo '-%F{#ff00f7}('$branch')%f'
  fi
}

# Enable substitution in the prompt.
setopt prompt_subst

# Config for prompt. PS1 synonym.
prompt='%F{#1dc223}%n%f@%F{#00ffd0}%1~%f$(git_branch_name)$ '

This is the code I have on .zshrc file, and "git_branch_name" is the function to get the branch name on my terminal.

It is working fine for all branches but when I have a branch that name including forward slash (/), it's giving me last chunk only.

Example: branch name: main -> main branch name: feat/process -> process

But I need the full branch name "feat/process".


Solution

  • This has nothing to do with Linux, macOS, or Terminal, and very little to do with Git: it's because you told awk to print just the last slash-separated component:

    awk 'BEGIN{FS="/"} {print $NF}'
    

    If you don't want just the last slash-separated component, don't ask for that. There's no need to use awk here at all: use git rev-parse --abbrev-ref HEAD to produce the abbreviated name of the current branch, if there is a current branch, or HEAD if not; or use git symbolic-ref --short HEAD to produce the abbreviated name of the current branch, or an error if there is no current branch.