什么是最好的便携式(POSIX?)方法来脚本找到链接的目标,如果readlink和realpath不可用?
你会ls -l,如果它开始时带有l文本->,sed并重复,直到它不再开始l?
Per BashFAQ#29(也赞同@EugeniuRosca建议的GNU查找方法):
一种广泛可用(但不是纯POSIX)选项是使用perl:
target=/path/to/symlink-name perl -le 'print readlink $ENV{target}'
Run Code Online (Sandbox Code Playgroud)
如果保证符号链接的名称不包含->,则可以解析输出ls.
以下代码结合了两种方法:
# define the best readlink function available for this platform
if command -v readlink >/dev/null 2>/dev/null; then
# first choice: Use the real readlink command
readlink() {
command readlink -- "$@"
}
elif find . -maxdepth 0 -printf '%l' >/dev/null 2>/dev/null; then
# second choice: use GNU find
readlink() {
local ll candidate >/dev/null 2>&1 ||:
if candidate=$(find "$1" -maxdepth 0 -printf '%l') && [ "$candidate" ]; then
printf '%s\n' "$candidate"
else
printf '%s\n' "$1"
fi
}
elif command -v perl >/dev/null 2>/dev/null; then
# third choice: use perl
readlink() {
local candidate ||:
candidate=$(target=$1 perl -le 'print readlink $ENV{target}')
if [ "$candidate" ]; then
printf '%s\n' "$candidate"
else
printf '%s\n' "$1"
fi
}
else
# fourth choice: parse ls -ld
readlink() {
local ll candidate >/dev/null 2>&1 ||:
ll=$(LC_ALL=C ls -ld -- "$1" 2>/dev/null)
candidate=${ll#* -> }
if [ "$candidate" = "$ll" ]; then
printf '%s\n' "$1"
else
printf '%s\n' "$candidate"
fi
}
fi
readlink_recursive() {
local path prev_path oldwd found_recursion >/dev/null 2>&1 ||:
oldwd=$PWD; path=$1; found_recursion=0
while [ -L "$path" ] && [ "$found_recursion" = 0 ]; do
if [ "$path" != "${path%/*}" ]; then
cd -- "${path%/*}" || {
cd -- "$oldwd" ||:
echo "ERROR: Directory '${path%/*}' does not exist in '$PWD'" >&2
return 1
}
path=${PWD}/${path##*/}
fi
path=$(readlink "$path")
if [ -d "$path" ]; then
cd -- "$path"
path=$PWD
break
fi
if [ "$path" != "${path%/*}" ]; then
cd -- "${path%/*}" || {
echo "ERROR: Could not traverse from $PWD to ${path%/*}" >&2
return 1
}
path=${PWD}/${path##*/}
elif [ "$PWD" != "$oldwd" ]; then
path=${PWD}/$path
fi
for prev_path; do
if [ "$path" = "$prev_path" ]; then
found_recursion=1
break
fi
done
set -- "$path" "$@" # record path for recursion check
done
if [ "$path" != "${path%/../*}" ]; then
cd "${path%/*}" || {
echo "ERROR: Directory '${path%/*}' does not exist in $PWD" >&2
return 1
}
printf '%s\n' "$PWD/${path##*/}"
else
printf '%s\n' "$path"
fi
cd -- "$oldwd" ||:
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
975 次 |
| 最近记录: |