11

How can I create a bash and a zsh prompt that shows only the current directory and its parent directory?

For example, if I'm at the dir ~/pictures/photos/2021, it should show:

[photos/2021]$ echo hi

That's all. Would like it for bash and for zsh.

1

2 Answers 2

16

In zsh:

PS1='[%2d] $ '

See info zsh 'prompt expansion' for details.

In bash (or zsh -o promptsubst, though you wouldn't want to do that there as if $PWD contains % characters, that would cause further prompt expansions):

PS1='[${PWD#"${PWD%/*/*}/"}] $ '
10
  • how PWD expand within single quotes? or maybe it does differently for the PS1 or prompts? really I cannot understand how it is expanded! May 24, 2021 at 13:30
  • @αғsнιη, it's not expanded at the time of assignment, but it's expanded each time the prompt is expanded as part of the prompt expansion. May 24, 2021 at 13:36
  • seems it removes outer quotes then perform variable expansions, etc, is it safe? looks for me it's unsafe if one don't know what they do with it. I didn't know this until today! like for a directory named ; reboot; May 24, 2021 at 13:37
  • 3
    @αғsнιη, it's as safe as your $PS1 is. If you set PS1='$(reboot)', then it will reboot of course. That's why you don't want to set $PS1 to arbitrary values without sanitizing them as part of your PROMPT_COMMAND in bash. In zsh, if you enable the promptsubst option, it's a bit worse in that %x expansions are done after those expansions. It's safer to use the $psvar array and precmd() there than enabling prompsubst. May 24, 2021 at 13:43
  • 2
    @αғsнιη, PS1='$PWD' is safe in that case in that expansion is not going to be done recursively. $PWD will be expanded to its value, but if that value has some $s or backticks, that will not be further expanded. The prompt would be if you your $PROMPT_COMMAND does something like PS1="$PWD ... " (note the double quotes) May 24, 2021 at 13:52
3

Another option that may be more readable:

PS1='[$(basename $(dirname "$PWD"))/$(basename "$PWD")]'

This also shows how you do similar directory operations more generally.

1
  • 3
    Note that that solution is for bash or other shells that perform other expansions upon prompt expansions. There's a minor glitch in that it gives /// when you're in / or //etc when in /etc for instance. It does strip trailing newline characters in those path components. It means starting at least 3 processes and executing three external processes in them at each prompt. So in the end, I wouldn't go for that approach. May 25, 2021 at 5:39

You must log in to answer this question.