2

I would like to display only the first two letters of the current directory.

I tried

PROMPT="%1d %# " 

which displays the current directory as directory1. But taking a subset of the directory as the first two characters and displaying as the zsh prompt in MacOS is where I am lost.

How do I only get the first two characters, i.e. di instead of directory1 as the zsh prompt instead?

4
  • What if you have dir $ and you cd to directory2? Is it now dir/dir $? Commented Jul 23, 2023 at 1:04
  • As a general advice, you can get your prompt to be "anything", if you define cd as a function, in which you calculate an updated prompt. Commented Jul 23, 2023 at 1:12
  • @Kaz - with zsh you can use a precommand to execute arbitrary code to set the prompt. Commented Jul 23, 2023 at 1:48
  • On MacOS, a home directory usually has several standard subdirectories. Two of them are named Documents and Downloads. Since they have the same first two letters, your prompt won't tell you which one you're in. Are you sure you don't want the prompt to be the first three or four letters of the directory name? Commented Jul 29, 2023 at 9:42

2 Answers 2

2

You can use the %2>...> truncating operator to truncate %1~ (the last component of the current working directory with ~ representation) or %1d if you don't want the tilde representations:

$ PROMPT='before %2>>%1~%>> after%# ' before ~ after% cd /usr/local before lo after% cd ~sys before ~s after% 

Or to show that there has been some truncation:

$ PROMPT='before %3>✀>%1d%>> after%# ' before ch✀ after% cd /usr/local before lo✀ after% cd / before / after% 
0

Try this:

setopt promptsubst PROMPT='${${(%):-%1d}[1,2]}%#' 

This is a set of nested zsh expansions, which can be a bit challenging to read at first. Some of the pieces:

  • setopt promptsubst- with this enabled, zsh will expand the ${..}s in the prompt.
  • PROMPT='...' - sets the prompt. The single quotes are important; we do not want to evaluate the ${...} expansions until later.
  • %# - # if root, % otherwise.
  • ${:-...} - this is a way to get a constant string (%1d) into a nested expansion.
  • ${(%)...} - percent sequences are processed as prompt sequences. We need this since the ${...} expansions took us out of 'prompt world' into 'normal variable world'.
  • %1d - the last component of the current directory. For /a/b/c/ddd, this will be ddd.
  • ${...[1,2]} - the first two characters in the string. Note that arrays in zsh start with index 1.

There is more information in the zsh documentation.

1
  • When using promptsubst, you need to make sure %s (and possibly ! if promptbang is enabled) are escaped in the expansions. See for instance after mkdir %Bar; cd %Bar Commented Jul 28, 2023 at 8:50

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.