即使是当前版本的 OSX (10.11.3) 也没有附带realpath
实用程序,因此您的实用程序必须确实来自 GNU coreutils
Homebrew 包。
事实上,你可以很容易地用realpath
它自己来验证;例如:
$ realpath "$(which realpath)"
/usr/local/Cellar/coreutils/8.24/bin/grealpath
在Bujiraso 的有用答案中,使用--relative-base="$HOME"
并简单地添加是您情况下最简单的解决方案。~/
让我提出一个替代方案:
absPath=$(perl -MCwd -le 'print Cwd::abs_path(shift)' "script.sh")
abstractPath="\$HOME${absPath#"$HOME"}"
结果将类似于literal $HOME/bin/script.sh
,当由 shell 解释时,将扩展为当时特定于当前用户的路径。
如果您定义abstractHomePath()
bash
如下打印的函数,则可以使用:
abstractPath=$(abstractHomePath "script.sh") # -> '$HOME/bin/script.sh'
abstractHomePath
重击功能:
# Given a relative or absolute path, returns an absolute path in which the path
# prefix that is the current user's home directory is replaced with literal
# '$HOME' so as to yield an abstract path that can later be expanded in a
# different user's context to get the analogous path.
#
# If the input path resolves to an absolute path that is *not* prefixed with
# the current user's home diretory path, the absolute path is returned as -is.
#
# Note that any symlinks in the path are resolved to their ultimate targets
# first and that the path is normalized.
#
# Examples:
# abstractHomePath ~ # -> '$HOME'
# abstractHomePath /Users/jdoe/Downloads # -> '$HOME/Downloads'
# abstractHomePath /tmp # -> '/private/tmp' - symlink resolved, but no $HOME prefix
# Prerequisites:
# Requires Perl v5+
abstractHomePath() {
local absPath=$(perl -MCwd -le 'print Cwd::abs_path(shift)' "$1")
if [[ $absPath == "$HOME"* ]]; then
printf '%s\n' "\$HOME${absPath#"$HOME"}"
else
printf '%s\n' "$absPath"
fi
}