Skip to main content

Conditional statement in a function for PS1 are not re-evalutated [Resolved]

I'm using a function to dynamically generate output for PS1. There are a couple statements that check if node and package.json exist, and if git and .git folder exist to display node version or the git branch. If none exist it just outputs the User$.

The problem is when user goes into another folder where none of the conditions are met the prompt is not updating. It's like conditions are cached or smth

function displayPS1() {
  MESSAGE="";
  GRAY_BACK="\[\e[100;97m\]";
  GREEN_BACK="\[\e[100;42m\]";
  GREEN_FORE="\[\e[32;1m\]";
  CYAN_BACK="\[\e[100;46m\]";
  CYAN_FORE="\[\e[36;1m\]";
  RESET="\[\e[0m\]";

  if hash node 2>/dev/null && [ -e package.json ]; then
    NODE='$(node -v | sed "s/\(v[0-9]*\)\(\.[0-9]*\.[0-9]*\)/\1/g")';
    MESSAGE="${GRAY_BACK} node ${GREEN_BACK} $NODE ${RESET} User${GREEN_FORE}$ ${RESET}";
  elif hash git 2>/dev/null && [ -d .git ]; then
    BRANCH='$(cat .git/HEAD | sed "s/ref:[[:space:]]refs\/heads\///")';
    MESSAGE="${GRAY_BACK} git ${CYAN_BACK} $BRANCH ${RESET} User${CYAN_FORE}$ ${RESET}";
  else
    MESSAGE="User${CYAN_FORE}$ ${RESET}";
  fi

  echo "$MESSAGE";
}
export PS1=$(displayPS1);

Question Credit: Mr. Madamin
Question Reference
Asked July 21, 2019
Tags: bash, prompt
Posted Under: Unix Linux
19 views
2 Answers

export PS1=$(displayPS1);

This will run displayPS1, and the if statements within once, assigning the result to the prompt. The conditions won't be processed again after that.

Instead, put the function call in PROMPT_COMMAND, so it gets called every time the prompt is going to be printed. So either

PROMPT_COMMAND='PS1=$(displayPS1)'

or perhaps rather

PROMPT_COMMAND=setPS1

and make setPS1 a function that sets PS1 itself. (Getting rid of the command substitution saves a fork from the subshell invocation every time the prompt is changed.)


credit: ilkkachu
Answered July 21, 2019

Use the quotes.

PS1='$(displayPS1)'

If you don't then the function is evaluated at assignment time.


credit: Kusalananda
Answered July 21, 2019
Your Answer
D:\Adnan\Candoerz\CandoProject\vQA