Make pwd result in terms of "~"?

If your're using bash, then the dirs builtin has the desired behavior:

dirs +0
~/some/random/folder

(Note +0, not -0.)

With zsh:

dirs
~/some/random/folder

To be exactly, we first need to clear the directory stack, else dirs would print all contents:

dirs -c; dirs

Or with zsh's print builtin:

print -rD $PWD

or

print -P %~

(that one turns prompt expansion on. %~ in $PS1 expands to the current directory with $HOME replaced with ~ but also handles other named directories like the home directory of other users or named directories that you define yourself).


You can use Bash variable substring replacement feature:

$ pwd
/home/vagrant/foo/bar
$ echo ${PWD/#$HOME/'~'}
~/foo/bar

Using sed:

pwd | sed "s|^$HOME|~|"

The idea is to use any character that is less likely to appear in a home directory path as the delimiter in sed regex. In the example above I am using |.

The good thing about this technique is that it is actually shell-independent.

You can also alias pwd to /bin/pwd | sed "s|$HOME|~|" to get this behavior in other scripts that might be using pwd.