Camander
Camander

Reputation: 147

Get '~' Abbreviated Path in Bash

I came across a problem that I feel should be rather simple, but I cant seem to figure out the answer.

I am trying to abbreviate paths in bash with the '~' similar to how the prompt does.

For example, if I had the path

/home/user/temp/file1

I would like to turn it into

~/temp/file1

Is there a simple way to do this? Or am I going to need to figure out how to compare parts of strings?

Upvotes: 2

Views: 788

Answers (1)

chepner
chepner

Reputation: 531325

For the current user, you can use the substring substitution operator:

$ path=/home/user/foo/bar
$ echo $HOME
/home/user
$ echo ${path/#$HOME/\~}
~/foo/bar

For arbitrary users, I don't know of a simple solution.

Upvotes: 3

Related Questions