[英]Is there a good way to replace home directory with tilde in bash?
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.我正在尝试使用路径并用 bash 中的波浪号替换主目录,我希望尽可能少地使用必要的外部程序来完成它。 Is there a way to do it with just bash. I got
有没有办法只用 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] = '\0';
return (tdir);
}
else
return (name);
}
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:我不知道有什么方法可以直接将其作为变量替换的一部分,但您可以将其作为命令来执行:
[[ "$name" =~ ^"$HOME"(/|$) ]] && name="~${name#$HOME}"
Note that this doesn't do exactly what you asked for: it replaces "/home/alice/" with "~/" rather than "~".请注意,这并不完全符合您的要求:它将“/home/alice/”替换为“~/”而不是“~”。 This is intentional, since there are places where the trailing slash is significant (eg
cp -R ~ /backups
does something different from cp -R ~/ /backups
).这是有意为之的,因为有些地方的尾部斜杠很重要(例如
cp -R ~ /backups
做的事情与cp -R ~/ /backups
不同)。
See this unix.stackexchange answer :请参阅此 unix.stackexchange 答案:
If you're using bash, then the
dirs
builtin has the desired behavior:如果您使用的是 bash,则内置的
dirs
具有所需的行为:dirs +0 ~/some/random/folder
That probably uses Bash's own C code that you pasted there.这可能使用了您粘贴在那里的 Bash 自己的 C 代码。 :)
:)
And here's how you could use it:以下是您可以如何使用它:
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)
Note that this will only work with directory names that already exist.请注意,这仅适用于已经存在的目录名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.