Im trying to work with a path and replace the home directory with a tilde in bash, Im hoping to get it done with as little external programs as necessary. Is there a way to do it with just bash. I got
${PWD/#$HOME/\~}
But thats not quite right. It needs to convert:
/home/alice to ~
/home/alice/ to ~/
/home/alice/herp to ~/herp
/home/alicederp to /home/alicederp
As a note of interest, heres how the bash source does it when converting the \w value in the prompt:
/* Return a pretty pathname. If the first part of the pathname is
the same as $HOME, then replace that with `~'. */
char *
polite_directory_format (name)
char *name;
{
char *home;
int l;
home = get_string_value ("HOME");
l = home ? strlen (home) : 0;
if (l > 1 && strncmp (home, name, l) == 0 && (!name[l] || name[l] == '/'))
{
strncpy (tdir + 1, name + l, sizeof(tdir) - 2);
tdir[0] = '~';
tdir[sizeof(tdir) - 1] = '\0';
return (tdir);
}
else
return (name);
}
print -D $PWD
.