32

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);
}
7
  • This is not bash, more like C code. But replacing a string with almost no context is error prone. you sure you want to proceed that way?
    – pizza
    Commented Apr 5, 2012 at 21:48
  • 1
    Sorry if this wasn't clear. The C code is an example of how to do it. Its how bash itself does it. bash being a program written in C. Now I want to do the same in the bash language.
    – Jake
    Commented Apr 5, 2012 at 21:58
  • 1
    Can you tell us what it outputs as it is right now?
    – wkl
    Commented Apr 5, 2012 at 22:22
  • 1
    Ok, when I said almost no context, there is actually quite a risk to do such a thing. the "~" expansion is only valid in a shell environment. So ~ -> home directory expansion is a shell feechure, if you really try to open a file from other than bash, it will fail. for example fopen("~/.bashrc","r") in C gives 0, not what you might expect.
    – pizza
    Commented Apr 5, 2012 at 22:33
  • 3
    zsh users: In zsh, this is just print -D $PWD.
    – Kevin
    Commented Dec 18, 2015 at 21:15

2 Answers 2

22

I don't know of a way to do it directly as part of a variable substitution, but you can do it as a command:

[[ "$name" =~ ^"$HOME"(/|$) ]] && name="~${name#$HOME}"

Note that this doesn't do exactly what you asked for: it replaces "/home/alice/" with "~/" rather than "~". This is intentional, since there are places where the trailing slash is significant (e.g. cp -R ~ /backups does something different from cp -R ~/ /backups).

6
  • 1
    @Steinar: It should do what you want -- the ${name#$HOME} part takes $name and removes $HOME from the front (i.e. "/documents" in your example). Is it possible you had a typo in it? Commented Feb 28, 2013 at 15:50
  • 1
    @Dennis: Steinar's solution has the same bug that "${PWD/#$HOME/\~}" has -- in OP's example, it'd turn "/home/alicederp" into "~derp". This can be fixed, but at the cost of losing a fair bit of that readability. Also, if you do use it, please double-quote the variable reference (i.e. echo "$name") to limit unexpected parsing. Commented Dec 29, 2013 at 6:53
  • if you don't have support for [[ =~ ]] *cough*msys*cough* you can also get it done with tildewd=$(pwd | sed -E "s-^$HOME($|(/.*))-~\2-").
    – danwyand
    Commented Aug 13, 2014 at 18:36
  • Does the assignment replace all occurrences of $HOME with ~, or just the first one? In the former case, it should be fixed. Commented Sep 15, 2019 at 15:23
  • 1
    @MihaiDanila It only replaces $HOME at the beginning of the string. Commented Sep 15, 2019 at 19:09
17

See this unix.stackexchange answer:

If you're using bash, then the dirs builtin has the desired behavior:

dirs +0
~/some/random/folder

That probably uses Bash's own C code that you pasted there. :)

And here's how you could use it:

dir=...    # <- Use your own here.

# Switch to the given directory; Run "dirs" and save to variable.
# "cd" in a subshell does not affect the parent shell.
dir_with_tilde=$(cd "$dir" && dirs +0)

Note that this will only work with directory names that already exist.

3
  • You could do dir_with_tilde="$(cd "${dir}" && dirs +0)" as a one-liner... But, this doesn't work if the directory doesn't exist, since you can't change to a non-existent directory. You might be constructing a path to create and want to log it in a friendly way. Commented Nov 29, 2017 at 0:53
  • Yeah, this is a better way that I suggested below. Thanks for the tip on the dirs command :) Commented May 30, 2018 at 23:58
  • 1
    dirs +0 doesn't work in zsh, but here's a variant that works on both zsh and bash: dirs -p | head -1
    – AbePralle
    Commented Jul 29, 2023 at 20:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.