bashunixprompt

Bash prompt spacing issue


So I found a cool bash prompt from this reddit thread

The one I was testing out was the top comment by @khordes. Here is what is expected:

Expected output

However, I get something a little different. Here is where the issue is:

───[~]───[      33 files, 2334400]

As you can see there is quite a lot of space before the number of files. The actual code is here:

PS1="┌─[\`if [ \$? = 0 ]; then echo \[\e[32m\]✔\[\e[0m\]; else echo \[\e[31m\]✘\[\e[0m\]; fi\`]───[\[\e[01;49;39m\]\u\[\e[00m\]\[\e[01;49;39m\]@\H\[\e[00m\]]───[\[\e[1;49;34m\]\W\[\e[0m\]]───[\[\e[1;49;39m\]\$(ls | wc -l) files, \$(ls -lah | grep -m 1 total | sed 's/total //')\[\e[0m\]]\n└───▶ "

Any input on how to fix that would be greatly appreciated.


Solution

  • This prompt uses $(ls | wc -l) to list files in the current directory.

    On GNU platforms, wc -l has no preceding whitespace when not passed any filenames.

    On BSD platforms (such as MacOS), the number is prefixed with spaces.

    Thus, the author of this prompt presumably tested it on a Linux variant or other GNU platform, and I'm presuming that you're running MacOS or another BSD. To be consistent, you need to ensure that such space is removed -- or switch to a mechanism for listing files that doesn't depend on wc, such as that given in BashFAQ #4.

    One alternative is the following:

    $(shopt -s nullglob; set -- *; echo "$#")