bash 有没有一种在bash中用波浪号替换主目录的好方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10036255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a good way to replace home directory with tilde in bash?
提问by Jake
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
我正在尝试使用路径并在 bash 中用波浪号替换主目录,我希望尽可能少地使用必要的外部程序来完成它。有没有办法只用 bash 来做到这一点。我有
${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:
作为一个有趣的注释,这里是 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] = 'dirs +0
~/some/random/folder
';
return (tdir);
}
else
return (name);
}
采纳答案by Mihai Danila
See this unix.stackexchange answer:
If you're using bash, then the
dirsbuiltin has the desired behavior:dirs +0 ~/some/random/folder
如果您使用的是 bash,则
dirs内置函数具有所需的行为: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)
That probably uses Bash's own C code that you pasted there. :)
这可能使用了您粘贴在那里的 Bash 自己的 C 代码。:)
And here's how you could use it:
以下是您如何使用它:
[[ "$name" =~ ^"$HOME"(/|$) ]] && name="~${name#$HOME}"
Note that this will only work with directory names that already exist.
请注意,这仅适用于已存在的目录名称。
回答by Gordon Davisson
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:
我不知道有什么方法可以将其作为变量替换的一部分直接执行,但您可以将其作为命令执行:
##代码##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 ~ /backupsdoes something different from cp -R ~/ /backups).
请注意,这并不完全符合您的要求:它将“/home/alice/”替换为“~/”而不是“~”。这是故意的,因为有些地方尾部斜杠很重要(例如,cp -R ~ /backups与 不同cp -R ~/ /backups)。

