注: これは堅固で移植可能な既製のソリューションであると信じていますが、そのために常に時間がかかります。
以下は、完全に POSIX に準拠したスクリプト/関数であり、したがってクロスプラットフォームです( 10.12 (Sierra) の時点でreadlink
はまだサポートされていないmacOS でも動作します) - POSIX シェル言語機能と POSIX 準拠のユーティリティ呼び出しのみを使用します。 .-f
これは、GNUreadlink -e
(のより厳密なバージョンreadlink -f
) の移植可能な実装です。
、、およびでスクリプトを実行するsh
か、関数をソースとしてbash
ksh
zsh
実行できます。
たとえば、スクリプト内で次のように使用して、実行中のスクリプトの元の真のディレクトリを取得し、シンボリックリンクを解決できます。
trueScriptDir=$(dirname -- "$(rreadlink "$0")")
rreadlink
スクリプト/関数定義:
コードは、この回答から感謝の気持ちを込めて適応されました。Node.js がインストールされている場合は、 でインストールできるベースのスタンドアロン ユーティリティ バージョンもここ
で
作成しました。bash
npm install rreadlink -g
#!/bin/sh
# SYNOPSIS
# rreadlink <fileOrDirPath>
# DESCRIPTION
# Resolves <fileOrDirPath> to its ultimate target, if it is a symlink, and
# prints its canonical path. If it is not a symlink, its own canonical path
# is printed.
# A broken symlink causes an error that reports the non-existent target.
# LIMITATIONS
# - Won't work with filenames with embedded newlines or filenames containing
# the string ' -> '.
# COMPATIBILITY
# This is a fully POSIX-compliant implementation of what GNU readlink's
# -e option does.
# EXAMPLE
# In a shell script, use the following to get that script's true directory of origin:
# trueScriptDir=$(dirname -- "$(rreadlink "$0")")
rreadlink() ( # Execute the function in a *subshell* to localize variables and the effect of `cd`.
target=$1 fname= targetDir= CDPATH=
# Try to make the execution environment as predictable as possible:
# All commands below are invoked via `command`, so we must make sure that
# `command` itself is not redefined as an alias or shell function.
# (Note that command is too inconsistent across shells, so we don't use it.)
# `command` is a *builtin* in bash, dash, ksh, zsh, and some platforms do not
# even have an external utility version of it (e.g, Ubuntu).
# `command` bypasses aliases and shell functions and also finds builtins
# in bash, dash, and ksh. In zsh, option POSIX_BUILTINS must be turned on for
# that to happen.
{ \unalias command; \unset -f command; } >/dev/null 2>&1
[ -n "$ZSH_VERSION" ] && options[POSIX_BUILTINS]=on # make zsh find *builtins* with `command` too.
while :; do # Resolve potential symlinks until the ultimate target is found.
[ -L "$target" ] || [ -e "$target" ] || { command printf '%s\n' "ERROR: '$target' does not exist." >&2; return 1; }
command cd "$(command dirname -- "$target")" # Change to target dir; necessary for correct resolution of target path.
fname=$(command basename -- "$target") # Extract filename.
[ "$fname" = '/' ] && fname='' # !! curiously, `basename /` returns '/'
if [ -L "$fname" ]; then
# Extract [next] target path, which may be defined
# *relative* to the symlink's own directory.
# Note: We parse `ls -l` output to find the symlink target
# which is the only POSIX-compliant, albeit somewhat fragile, way.
target=$(command ls -l "$fname")
target=${target#* -> }
continue # Resolve [next] symlink target.
fi
break # Ultimate target reached.
done
targetDir=$(command pwd -P) # Get canonical dir. path
# Output the ultimate target's canonical path.
# Note that we manually resolve paths ending in /. and /.. to make sure we have a normalized path.
if [ "$fname" = '.' ]; then
command printf '%s\n' "${targetDir%/}"
elif [ "$fname" = '..' ]; then
# Caveat: something like /var/.. will resolve to /private (assuming /var@ -> /private/var), i.e. the '..' is applied
# AFTER canonicalization.
command printf '%s\n' "$(command dirname -- "${targetDir}")"
else
command printf '%s\n' "${targetDir%/}/$fname"
fi
)
rreadlink "$@"
セキュリティの接線:
jarnoは、ビルトインcommand
が同じ名前のエイリアスまたはシェル関数によって隠されないようにする関数に関して、コメントで尋ねます。
unalias
またはunset
と[
がエイリアスまたはシェル関数として設定されている場合はどうなりますか?
rreadlink
が元の意味を持つようにすることの背後にある動機は、お気に入りのオプションを含めるように再定義するなど、対話型シェルで標準コマンドをシャドウするためによく使用される便利なエイリアスと関数command
をバイパスするために使用することです。ls
unalias
信頼されていない悪意のある環境を扱っていない限り、または、さらに言えば、、、... - 再定義されることを心配するunset
ことは問題ではないと言って差し支えありません。while
do
関数が本来の意味と動作を持つために依存しなければならないものがあります - それを回避する方法はありません。
POSIX ライクなシェルではビルトインの再定義が可能であり、言語キーワードでさえも、本質的にセキュリティ リスクです (そして偏執的なコードを書くことは一般的に困難です)。
あなたの懸念に具体的に対処するには:
関数は、元の意味を持つことにunalias
依存しています。それらの動作を変更する方法でシェル関数unset
として再定義することは問題になります。コマンド名 (の一部)を引用すると (例: ) エイリアスが回避されるため、エイリアスとしての再定義は必ずしも問題ではありません。\unalias
ただし、引用符はシェルキーワード( 、、、、 ...)のオプションではありません。また、シェル キーワードはシェル関数よりも優先されますが、 inおよびエイリアスは最も優先度が高いため、シェル キーワードの再定義を防ぐには、次のコマンドを使用して実行する必要があります。それらの名前 (ただし、非対話型シェル (スクリプトなど) では、エイリアスはデフォルトでは展開されません-が最初に明示的に呼び出された場合のみ)。while
for
if
do
bash
zsh
unalias
bash
shopt -s expand_aliases
unalias
ビルトインとして、元の意味を持つようにするには、最初に on を使用する必要があります。\unset
これにunset
は、元の意味を持つ必要があります。
unset
はシェルの組み込みであるため、そのように呼び出されるようにするには、それ自体が関数として再定義されていないことを確認する必要があります。引用符でエイリアス形式をバイパスすることはできますが、シェル関数形式 (catch 22) をバイパスすることはできません。
したがって、私が知る限り、その元の意味を信頼できない限り、unset
すべての悪意のある再定義から防御する保証された方法はありません。