1001Ferramentas
💲 Dev

Bash PS1 Generator

Compose PS1 with ANSI colors, user, host, pwd, git branch and last exit code. Live prompt preview.

PS1:

Preview aproximado:

Building a bash prompt without memorising the codes

The variable defining the bash prompt takes a collection of backslash escapes: user, host, directory, time, the symbol that changes depending on whether you are root. Memorising that does not pay off — there are more than twenty codes and nobody touches their prompt often enough to retain them.

Pick the elements and the colours and the page assembles the variable. The technical detail causing the most trouble shows up right there: colour sequences must sit between the non-printing start and end markers. Without them, bash counts the invisible colour characters in the prompt length, and the result is the command line overwriting itself when you scroll history or edit a long command.

To apply permanently, the definition goes in the file read by interactive shells, typically ~/.bashrc. Worth remembering that there is also the continuation prompt variable, the one appearing when a command is incomplete, and the trace one used when script debugging is enabled — if you have ever got lost in a script with many repeated lines, configuring that last one with the line number helps a great deal.

Frequently asked questions

Why does my prompt scramble when I scroll history?
Because the colour sequences are not wrapped in the non-printing markers. Bash uses character count to know where the cursor is; counting the invisible ones, it misjudges the position and the text overwrites itself. It is the most common defect in prompts copied off the internet.
How do I show the Git branch in the prompt?
By calling a function inside the variable. The catch is using single quotes in the definition, so the command is evaluated on every prompt rather than once. And mind the cost: every prompt then runs a Git command, which becomes noticeable in a very large repository.
Can I show the previous command's exit code?
You can, and it is genuinely useful: capture the value at the very start and display it conditionally, and the prompt shows the code only when the command failed. Order matters — the capture has to come first, before any other command inside the prompt overwrites the value.

Related Tools