[英]bash current working directory with '~' replacing path to home folder
Is there a way to echo current directory with ~
replacing home directory?有没有办法用
~
替换主目录来回显当前目录?
Example:例子:
~/inbox
instead of /home/john/inbox
~/inbox
而不是/home/john/inbox
Home directory should not be hardcoded.主目录不应硬编码。
There are $PWD
and $HOME
variables.有
$PWD
和$HOME
变量。
A built-in bash tool would be nice.内置的 bash 工具会很好。
echo "${PWD/#$HOME/\~}"
This substitutes $HOME
with ~
.这将
$HOME
替换$HOME
~
。 The #
is like ^
in a regex: it anchors the match to the beginning of the string. #
就像正则表达式中的^
:它将匹配锚定到字符串的开头。 The \\~
replaces $HOME
with a literal tilde; \\~
用文字代字号替换$HOME
; if we didn't use the \\
escape, the ~
would re-expand to $HOME
and effectively do nothing.如果我们不使用
\\
转义符, ~
将重新扩展为$HOME
并且实际上什么都不做。
这应该适用于任何 POSIX shell:
pwd | sed "s|^$HOME|~|"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.