現在のバージョンの OSX (10.11.3) でさえユーティリティが付属していないrealpath
ため、実際には GNU coreutils
Homebrew パッケージから入手する必要があります。
realpath
実際、それ自体で簡単に確認できます。例えば:
$ realpath "$(which realpath)"
/usr/local/Cellar/coreutils/8.24/bin/grealpath
ブジラソの役立つ答えのように、を使用--relative-base="$HOME"
して単純に先頭に追加するのが、あなたの場合の最も簡単な解決策です。~/
次の代替案を提案させてください。
absPath=$(perl -MCwd -le 'print Cwd::abs_path(shift)' "script.sh")
abstractPath="\$HOME${absPath#"$HOME"}"
結果はliteral のようなものになり$HOME/bin/script.sh
、シェルによって解釈されると、その時点で現在のユーザー固有のパスに展開されます。
以下に示すように関数を定義する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
}