有没有一种很好的方法用bash中的波浪号替换主目录?

Jak*_*ake 23 regex bash path

我试图使用一个路径并用bash中的波形符替换主目录,我希望用必要的外部程序完成它.有没有办法只用bash来做到这一点.我有

${PWD/#$HOME/\~}
Run Code Online (Sandbox Code Playgroud)

但那不太对劲.它需要转换:

/home/alice to ~
/home/alice/ to ~/
/home/alice/herp to ~/herp
/home/alicederp to /home/alicederp
Run Code Online (Sandbox Code Playgroud)

作为一个感兴趣的注释,继承人在转换提示符中\ w值时bash源如何做到这一点:

/* 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);
}
Run Code Online (Sandbox Code Playgroud)

Gor*_*son 14

我不知道如何直接将其作为变量替换的一部分,但您可以将其作为命令执行:

[[ "$name" =~ ^"$HOME"(/|$) ]] && name="~${name#$HOME}"
Run Code Online (Sandbox Code Playgroud)

请注意,这并不完全符合您的要求:它将"/ home/alice /"替换为"〜/"而不是"〜".这是故意的,因为有些地方的尾随斜线是显着的(例如,cp -R ~ /backups做了不同的事情cp -R ~/ /backups).


Mih*_*ila 10

看到这个unix.stackexchange答案:

如果你正在使用bash,那么dirs内置函数具有所需的行为:

dirs +0
~/some/random/folder
Run Code Online (Sandbox Code Playgroud)

这可能使用了你在那里粘贴的Bash自己的C代码.:)

这是你如何使用它:

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)
Run Code Online (Sandbox Code Playgroud)

请注意,这仅适用于已存在的目录名称.