1

I use zsh shell, with the %1~ parameter inside my prompt. Instead of displaying /home/username it displays ~, /home/username/Desktop changes to just Desktop.

I need to get the length of the prompt-displayed path programmatically, ie ~ would amount to just 1 character, while /home/username would use 14. Is there a way to do it without overcomplicating stuff?

10
  • 1
    Do you mean print -P '%1~'?
    – Kusalananda
    Commented Sep 22, 2021 at 22:51
  • I guess I wouldn't be able to mark it as the answer. Thank you
    – Gotoro
    Commented Sep 22, 2021 at 22:56
  • Well, it's a bit unclear what you want. On the one hand, it seems you want to get the prompt string (which that print command gives you); on the other it seems you want the string's length. I'm also confused because you mention the string /home/username, which %1~ would never generate.
    – Kusalananda
    Commented Sep 22, 2021 at 22:58
  • 1
    @Kusalananda Right, a bit of an XY problem, IMHO. The real question seems to be how to get the length of the prompt. But the question as phrased is how to get the actual output of the %1~ prompt expansion. I'm assuming that the reference to /home/username is because of an attempt to use $PWD or something like that, unsuccessfully. Commented Sep 22, 2021 at 23:05
  • 1
    It would be helpful to mention what you need the string length for to ensure you're not barking up the wrong tree when there's a different and better way to do what you need to do.
    – Kusalananda
    Commented Sep 23, 2021 at 5:39

1 Answer 1

1

To do prompt expansion other than at the prompt, there's

print -rP %1~

Or:

print -rPv expanded %1~

To store in a expanded variable.

Or use the % parameter expansion flag:

var=%1~
print -r -- ${(%)var}

Or to store in a variable:

expanded=${(%)var}

To get the length in number of characters:

length=${#${(%)var}}

But note that if there are colouring/bold/italic... directives, the length will also include the number of characters in the colouring escape sequences, you won't get the display width of the prompt expansion.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .