Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash current working directory with '~' replacing path to home folder

Tags:

linux

bash

shell

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

Example:
~/inbox instead of /home/john/inbox

Home directory should not be hardcoded.
There are $PWD and $HOME variables.
A built-in bash tool would be nice.

like image 936
kornieff Avatar asked Sep 20 '14 00:09

kornieff


People also ask

How do I change directory to home in bash?

Now when you open Git Bash and type pwd you should see the new folder is automatically where you are. To change your current directory to the users home directory type cd ~ . The ~ represents the home directory which is set in the %HOME% environment variable.

How do I change the current directory in bash?

To change directories, use the command cd followed by the name of the directory (e.g. cd downloads ). Then, you can print your current working directory again to check the new path.

How do I get current working directory in bash?

How do I get the current working directory under Bash or Ksh shell running on Linux or Unix like operating systems? [a] OLDPWD The previous working directory as set by the cd command. [b] PWD The current working directory as set by the cd command. pwd command – Print the name of the current working directory.


1 Answers

echo "${PWD/#$HOME/\~}"

This substitutes $HOME with ~. The # is like ^ in a regex: it anchors the match to the beginning of the string. The \~ replaces $HOME with a literal tilde; if we didn't use the \ escape, the ~ would re-expand to $HOME and effectively do nothing.

like image 113
John Kugelman Avatar answered Sep 28 '22 16:09

John Kugelman