Bash current working directory with '~' replacing the path to the home folder

Is there a way to echo the current directory with ~replacing the home directory?

Example:
~/inboxinstead/home/john/inbox

The home directory does not have to be hard-coded.
There are variables $PWDand $HOME.
The built-in bash tool will be nice.

+4
source share
2 answers
echo "${PWD/#$HOME/~}"

This replaces $HOMEwith ~. #similar to ^in regex: it binds a match to the beginning of a line.

+8
source

This should work under any POSIX shell:

pwd | sed "s|^$HOME|~|"
+3
source

All Articles