MacOS – How to print a path with a home directory replaced by ~ in terminal

bashmacosterminal

How can I print a path in Terminal with the home folder path replaced by a ~?

pwd
/Users/denz/projects/coolApp

But I want to something like this

~/projects/coolApp

Best Answer

Here's a function:

pwdr () {
  pwd | sed s,$HOME,~,
}

Add this function to a profile file and use pwdr.


In bash you can also use parameter expansion and avoid the call to sed by using the rather magically looking

echo ${PWD/~/\~}

The ${...} expression can be used anywhere a shell variable can be used as well, the echo is just for demonstration purposes.