How to modify w in PS1 conditionally?

Everything I work on lives inside the icloud directory, making my bash prompt very long:

~/Library/Mobile Documents/com~apple~CloudDocs/Projects/foo/bar/baz @master $ 

My prompt is:

PS1='w[e[1;35m]$(__git_ps1 " @%s") [e[1;32m]$[e[m] '

Is it possible to replace only the occurence of/Library/Mobile Documents/com~apple~CloudDocs/ in w into something like icloud thus producing a better prompt like the following?

~/icloud/Projects/foo/bar/baz @master $ 
Asked By: htor


Zsh has the "named directories" feature that pretty much automatically abbreviates the directory name in the prompt, too. I don’t think Bash has the equivalent, but you could work around it by having PROMPT_COMMAND run a custom function to set a variable you then print in the prompt insetad of using w.

E.g. this should replace an initial /tmp/test in the path with ~testdir.

set_promptpath() {
    # do whatever replacement you like here
PS1='$promptpath$ '
Answered By: ilkkachu

I solved it using parts of @ilkkachu’s answer by using a function cwd that updates the path dynamically:

cwd() {
    echo ${cwd/Library/Mobile Documents/com~apple~CloudDocs/icloud}
PS1='$(cwd)[e[1;35m]$(__git_ps1 " @%s") [e[1;32m]$[e[m] '

It’s not pretty, but at least my prompt is pretty again!

Answered By: htor
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.