繁体   English   中英

在bash中用波浪线替换主目录有什么好的方法吗?

[英]Is there a good way to replace home directory with tilde in bash?

我正在尝试使用路径并用 bash 中的波浪号替换主目录,我希望尽可能少地使用必要的外部程序来完成它。 有没有办法只用 bash 就可以做到这一点。我得到了

${PWD/#$HOME/\~}

但那并不完全正确。 它需要转换:

/home/alice to ~
/home/alice/ to ~/
/home/alice/herp to ~/herp
/home/alicederp to /home/alicederp

作为一个有趣的注释,这里是 bash 源代码在提示中转换 \w 值时是如何做到的:

/* 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);
}

我不知道有什么方法可以直接将其作为变量替换的一部分,但您可以将其作为命令来执行:

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

请注意,这并不完全符合您的要求:它将“/home/alice/”替换为“~/”而不是“~”。 这是有意为之的,因为有些地方的尾部斜杠很重要(例如cp -R ~ /backups做的事情与cp -R ~/ /backups不同)。

请参阅此 unix.stackexchange 答案

如果您使用的是 bash,则内置的dirs具有所需的行为:

 dirs +0 ~/some/random/folder

这可能使用了您粘贴在那里的 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)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM