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);
$(...)
). – choroba Jul 21 '19 at 13:07PS1
really does not need to be exported. It's just the shell using it. Also, runningnode
at least once, possibly twice for each prompt? Would it not be better to overload thecd
command? The prompt would not need to be re-evaluated unless you change directory (most of the time at least). – Kusalananda Jul 21 '19 at 14:14cd
. But what if someone removespackage.json
or node or git, we would need to overload those commands also @Kusalananda – Mr. Madamin Jul 21 '19 at 14:49cd
? I was thinking something simple, likecd () { builtin cd "$@"; PS1=$(displayPS1); }
. – Kusalananda Jul 21 '19 at 14:51