【发布时间】:2012-04-19 15:28:28
【问题描述】:
我正在尝试使用路径并用 bash 中的波浪号替换主目录,我希望使用尽可能少的外部程序来完成它。有没有办法只用bash来做到这一点。我得到了
${PWD/#$HOME/\~}
但这并不完全正确。它需要转换:
/home/alice to ~
/home/alice/ to ~/
/home/alice/herp to ~/herp
/home/alicederp to /home/alicederp
请注意,以下是 bash 源在转换 \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);
}
【问题讨论】:
-
这不是 bash,更像是 C 代码。但是替换几乎没有上下文的字符串很容易出错。你确定要那样做吗?
-
抱歉,如果不清楚。 C 代码是如何执行此操作的示例。它是 bash 本身如何做到的。 bash 是用 C 编写的程序。现在我想用 bash 语言做同样的事情。
-
你能告诉我们它现在的输出吗?
-
好吧,当我说几乎没有上下文的时候,实际上做这样的事情是有很大风险的。 "~" 扩展只在 shell 环境中有效。所以~->主目录扩展是一个shellfeechure,如果你真的尝试从bash以外的地方打开文件,它会失败。例如,C 中的 fopen("~/.bashrc","r") 给出 0,这不是您所期望的。
-
zsh 用户:在 zsh 中,这只是
print -D $PWD。