Score:5

How to add an unbroken line in bash starting from end of my left hand PS1 text to the right hand side

ru flag

I am having trouble wrapping my mind around this little problem

Basically Im using this bash PS1 script because its kinda cool:

PS1="\n \[\033[0;34m\]╭─────\[\033[0;31m\]\[\033[0;37m\]\[\033[41m\] \u \[\033[0m\]\[\033[0;31m\]\[\033[0;34m\]─────\[\033[0;32m\]\[\033[0;30m\]\[\033[42m\] \w \[\033[0m\]\[\033[0;32m\] \n \[\033[0;34m\]╰ \[\033[1;36m\]\$ \[\033[0m\]"

looks like this:

bash like powerline

What I want to do is print a time stamp on the right hand side with a solid line connecting the end of the left side to the beginning of the right side of the text, for example:

ben @ local ------------------------------------------12:00pm

I tried doing this:

$(printf '%*s' $COLUMNS  '-')

but that obviously just creates a whole new line filled with the dashes.

How do I get the value of where the curser left off, I see tput sc but I don't understand how to use that in a variable? Then print the lines, leaving maybe 5 characters on the right side for the time.

This is my first foray into bash scripting so forgive my ignorance.

Any help is appreciated

Score:7
cn flag

First, you have to strip escape sequences from the prompt string and expand it to get the real length to subtract the column length.

prompt_handler(){
    local A="$2[\A]"

    while [[ $A =~ \\[\x1b\\[[0-9\;]*m\\] ]]; do
       A=${A//"${BASH_REMATCH}"}
    done

    A=${A@P} \
    A=$((COLUMNS-${#A}))

    eval printf \
        -v A ─%.s {1..$A}

    PS1="$1$2${A}[\A]$3"
}

PROMPT_COMMAND='prompt_handler "\n" " \[\033[0;34m\]╭─────\[\033[0;31m\]\[\033[0;37m\]\[\033[41m\] \u \[\033[0m\]\[\033[0;31m\]\[\033[0;34m\]─────\[\033[0;32m\]\[\033[0;30m\]\[\033[42m\] \w \[\033[0m\]\[\033[0;32m\]" "\n \[\033[0;34m\]╰ \[\033[1;36m\]\$ \[\033[0m\]"'
terdon avatar
cn flag
This is really neat! It would benefit from some explanation though since you are using various bash features that will not be known by many. I had to look up the `${A@P}`, for instance, to learn that it is a special expansion mode that makes the variable be expanded as though it were a prompt string.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.