title: Is there a good way to replace home directory with tilde in bash?
body: <p>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</p>
  
  <pre><code>${PWD/#$HOME/\~}
  </code></pre>
  
  <p>But thats not quite right. It needs to convert:</p>
  
  <pre><code>/home/alice to ~
  /home/alice/ to ~/
  /home/alice/herp to ~/herp
  /home/alicederp to /home/alicederp
  </code></pre>
  
  <p>As a note of interest, heres how the bash source does it when converting the <a href="http://www.gnu.org/software/bash/manual/html_node/Printing-a-Prompt.html" rel="noreferrer">\w value in the prompt</a>:</p>
  
  <pre><code>/* 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 &gt; 1 &amp;&amp; strncmp (home, name, l) == 0 &amp;&amp; (!name[l] || name[l] == '/'))
      {
        strncpy (tdir + 1, name + l, sizeof(tdir) - 2);
        tdir[0] = '~';
        tdir[sizeof(tdir) - 1] = '\0';
        return (tdir);
      }
    else
      return (name);
  }
  </code></pre>