Kaunteya
Kaunteya

Reputation: 3090

Get actual prompt length

I wanted to print something like this on my gnome-terminal

[abc@host pwd]$ ************************************************************

using some manipulations in PS1 but the number of stars are dynamic depending on PS1 and terminal width. So can anyone plz suggest me the way to find out the length of PS1 i.e the actual string which will be displayed.

Upvotes: 5

Views: 1043

Answers (2)

Teemu Leisti
Teemu Leisti

Reputation: 3770

The current line length can be read from the Bash environment variable COLUMNS.

To set the prompt to always be a line of stars whose number is the exact width of the terminal at the time Enter is pressed (plus newlines at either end), include the following in ~/.bashrc:

function generate_prompt ()
{
    prompt="\n"
    for ((i = 0; i < $COLUMNS; i++)); do
        prompt+='*'
    done
    prompt+="\n"
    echo -e $prompt
}
export PS1="\$(generate_prompt)"

Note that if you omit the backslash in the definition of PS1, the line of stars will be generated at the time ~/.bashrc is evaluated, and it will remain the same length even if you change the terminal emulator's width. Including the backslash causes the function generate_prompt to be called each time you press Enter, making the line of stars always fit the current width of the terminal.

In case you wish to have some other output in the prompt, and then to fill the rest of the line with star characters, you'd have to subtract the length of that other output from $COLUMNS. I don't know how to do that.

Upvotes: 1

Zsolt Botykai
Zsolt Botykai

Reputation: 51673

It can't ve done portably IMO, as PS1 can contain escape sequences for color codes, (multiple) new lines too.

It can be calculated. But that's a really hard task. What if the user codes colorcodes in variable names (it's a common scenario), how to decide (during evaluation/counting the length) if that's something that the user wants to display or is only style information?

Upvotes: -3

Related Questions