我尝试使用路径并用 bash 中的波浪号替换主目录,我希望用尽可能少的外部程序来完成它。有没有办法只用bash来做到这一点。我有
${PWD/#$HOME/\~}
但这并不完全正确。它需要转换:
/home/alice to ~
/home/alice/ to ~/
/home/alice/herp to ~/herp
/home/alicederp to /home/alicederp
值得一提的是,在提示符中转换 \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);
}