Bash – Long-generating Bash prompt wraps incorrectly when I start typing

bashprompt

I have a Bash prompt that takes a while (~100-200ms) to generate, because it includes Git working tree status that takes some time to compute. Sometimes I start typing a command before it appears, but then the command wraps incorrectly.

Here is what I see in the terminal:

# I start typing:
some command...

# then the prompt appears:
some command...username [branch*] some/directory $ some command...

# then I type some more, causing the command to wrap:
some command...username [branch*] some/directory $ some command...wra
pping text 1

# and when I continue typing, the text overwrites the second line:
some command...username [branch*] some/directory $ some command...wra
wrapping text 2

Any idea how to prevent this?

Here is how my Bash prompt is set up:

# in .bashrc:
PROMPT_COMMAND="PS1=\`/home/username/my-prompt.sh\`"

# in /home/username/my-prompt.sh:
$PROMPT=...
$PROMPT+=...
echo -ne $PROMPT

I believe I set up all my \[ and \]s correctly inside $PROMPT. The issue appears only when I start typing before the prompt appears, and my command wraps.

Best Answer

It may work to disable terminal output while the prompt is generated:

PROMPT_COMMAND="PS1=\$(stty -echo)\`/home/username/my-prompt.sh\`\$(stty echo)"
Related Question