如何解析 shell 脚本中的符号链接
题
给定绝对或相对路径(在类 Unix 系统中),我想在解析任何中间符号链接后确定目标的完整路径。同时解决〜用户名符号的奖励积分。
如果目标是一个目录,则可以 chdir() 进入该目录,然后调用 getcwd(),但我真的想从 shell 脚本中执行此操作,而不是编写 C 帮助程序。不幸的是,shell 倾向于尝试向用户隐藏符号链接的存在(这是 OS X 上的 bash):
$ ls -ld foo bar
drwxr-xr-x 2 greg greg 68 Aug 11 22:36 bar
lrwxr-xr-x 1 greg greg 3 Aug 11 22:36 foo -> bar
$ cd foo
$ pwd
/Users/greg/tmp/foo
$
我想要的是一个函数resolve(),这样当从上面示例中的tmp目录执行时,resolve("foo") == "/Users/greg/tmp/bar"。
其他提示
readlink -f "$path"
编者注:以上适用于 GNU readlink
和 FreeBSD/PC-BSD/OpenBSD readlink
, , 但 不是 自 10.11 起在 OS X 上运行。
GNU readlink
提供额外的相关选项,例如 -m
用于解析符号链接,无论最终目标是否存在。
请注意,自 GNU coreutils 8.15 (2012-01-06) 起,有一个 真实路径 可用的程序比上述程序不那么迟钝并且更灵活。它还与同名的 FreeBSD util 兼容。它还包括生成两个文件之间的相对路径的功能。
realpath $path
对于 Mac OS X(至少 10.11.x),使用 readlink
没有 -f
选项:
readlink $path
编者注:这不会解析符号链接 递归地 因此不会报告 最终的 目标;例如,给定符号链接 a
这指向 b
, ,这又指向 c
, ,这只会报告 b
(并且不会确保它输出为 绝对路径).
使用以下内容 perl
OS X 上的命令来填补缺失的空白 readlink -f
功能:
perl -MCwd -le 'print Cwd::abs_path(shift)' "$path"
如果您只想要目录,“pwd -P”似乎可以工作,但如果由于某种原因您想要实际可执行文件的名称,我认为这没有帮助。这是我的解决方案:
#!/bin/bash
# get the absolute path of the executable
SELF_PATH=$(cd -P -- "$(dirname -- "$0")" && pwd -P) && SELF_PATH=$SELF_PATH/$(basename -- "$0")
# resolve symlinks
while [[ -h $SELF_PATH ]]; do
# 1) cd to directory of the symlink
# 2) cd to the directory of where the symlink points
# 3) get the pwd
# 4) append the basename
DIR=$(dirname -- "$SELF_PATH")
SYM=$(readlink "$SELF_PATH")
SELF_PATH=$(cd "$DIR" && cd "$(dirname -- "$SYM")" && pwd)/$(basename -- "$SYM")
done
我最喜欢的之一是 realpath foo
realpath - return the canonicalized absolute pathname realpath expands all symbolic links and resolves references to '/./', '/../' and extra '/' characters in the null terminated string named by path and stores the canonicalized absolute pathname in the buffer of size PATH_MAX named by resolved_path. The resulting path will have no symbolic link, '/./' or '/../' components.
readlink -e [filepath]
似乎正是您想要的 - 它接受了杂草路径,解决所有符号链接并返回“真实”路径 - 并且是“标准 *nix”,所有系统都可能已经拥有
其他方式:
# Gets the real path of a link, following all links
myreadlink() { [ ! -h "$1" ] && echo "$1" || (local link="$(expr "$(command ls -ld -- "$1")" : '.*-> \(.*\)$')"; cd $(dirname $1); myreadlink "$link" | sed "s|^\([^/].*\)\$|$(dirname $1)/\1|"); }
# Returns the absolute path to a command, maybe in $PATH (which) or not. If not found, returns the same
whereis() { echo $1 | sed "s|^\([^/].*/.*\)|$(pwd)/\1|;s|^\([^/]*\)$|$(which -- $1)|;s|^$|$1|"; }
# Returns the realpath of a called command.
whereis_realpath() { local SCRIPT_PATH=$(whereis $1); myreadlink ${SCRIPT_PATH} | sed "s|^\([^/].*\)\$|$(dirname ${SCRIPT_PATH})/\1|"; }
将一些给定的解决方案放在一起,知道 readlink 在大多数系统上都可用,但需要不同的参数,这对我来说在 OSX 和 Debian 上效果很好。我不确定 BSD 系统。也许需要的条件是 [[ $OSTYPE != darwin* ]]
排除 -f
仅来自 OSX。
#!/bin/bash
MY_DIR=$( cd $(dirname $(readlink `[[ $OSTYPE == linux* ]] && echo "-f"` $0)) ; pwd -P)
echo "$MY_DIR"
笔记:我相信这是一个可靠的、便携式的、现成的解决方案,它总是 冗长 正是因为这个原因。
下面是一个 完全符合 POSIX 标准的脚本/函数 因此 跨平台 (也适用于 macOS,其 readlink
还是不支持 -f
截至 10.12 (Sierra)) - 它仅使用 POSIX shell 语言特性 并且仅兼容 POSIX 的实用程序调用。
它是一个 GNU 的可移植实现 readlink -e
(更严格的版本 readlink -f
).
你可以 跑过 脚本 和 sh
或者 来源 功能 在 bash
, ksh
, , 和 zsh
:
例如,在脚本中,您可以按如下方式使用它来获取运行脚本的真实原始目录,并解析符号链接:
trueScriptDir=$(dirname -- "$(rreadlink "$0")")
rreadlink
脚本/函数定义:
该代码经过改编,感谢 这个答案.
我还创建了一个 bash
基于独立实用程序版本 这里, ,您可以使用它来安装
npm install rreadlink -g
, ,如果您安装了 Node.js。
#!/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 "$@"
安全问题的切线:
亚诺, ,参考确保内置的功能 command
没有被同名的别名或 shell 函数所遮蔽,在评论中询问:
如果什么
unalias
或者unset
和[
设置为别名或 shell 函数?
背后的动机 rreadlink
确保 command
它的本义就是用它来绕行(良性) 方便 别名和函数通常用于隐藏交互式 shell 中的标准命令,例如重新定义 ls
包括最喜欢的选项。
我认为可以肯定地说,除非您面对的是不受信任的恶意环境,担心 unalias
或者 unset
- 或者,就此而言, while
, do
, ...- 被重新定义不是一个问题。
有 某物 该函数必须依赖它才能具有其原始含义和行为 - 没有办法解决这个问题。
类似 POSIX 的 shell 允许重新定义内置函数甚至语言关键字 本质上 安全风险(编写偏执的代码通常很困难)。
具体解决您的疑虑:
该函数依赖于 unalias
和 unset
有其本来的意义。将它们重新定义为 外壳函数 以改变他们行为的方式将是一个问题;重新定义为 别名 不一定是一个问题,因为 引用 命令名称(的一部分)(例如, \unalias
) 绕过别名。
然而,引用是 不是 shell 的一个选项 关键词 (while
, for
, if
, do
, ...) 而 shell 关键字确实优先于 shell 功能, , 在 bash
和 zsh
别名具有最高优先级,因此为了防止 shell 关键字重新定义,您必须运行 unalias
和他们的名字(虽然在 非交互式 bash
shell(例如脚本)别名是 不是 默认扩展 - 仅当 shopt -s expand_aliases
首先被显式调用)。
为了保证 unalias
- 作为内置 - 有其原始含义,必须使用 \unset
首先,这需要 unset
有它原来的含义:
unset
是一个外壳 内置, ,因此为了确保它被这样调用,您必须确保它本身没有被重新定义为 功能. 。虽然您可以通过引用绕过别名形式,但无法绕过 shell 函数形式 - catch 22。
因此,除非你可以依赖 unset
就其本来意义而言,据我所知,没有一种有保证的方法可以防御所有恶意重新定义。
常见的 shell 脚本通常必须找到它们的“主”目录,即使它们是作为符号链接调用的。因此,脚本必须从 $0 开始找到它们的“真实”位置。
cat `mvn`
在我的系统上打印一个包含以下内容的脚本,这应该很好地提示您需要什么。
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
function realpath {
local r=$1; local t=$(readlink $r)
while [ $t ]; do
r=$(cd $(dirname $r) && cd $(dirname $t) && pwd -P)/$(basename $t)
t=$(readlink $r)
done
echo $r
}
#example usage
SCRIPT_PARENT_DIR=$(dirname $(realpath "$0"))/..
尝试这个:
cd $(dirname $([ -L $0 ] && readlink -f $0 || echo $0))
由于多年来我多次遇到过这种情况,而这一次我需要一个可以在 OSX 和 Linux 上使用的纯 bash 便携式版本,所以我继续编写了一个:
活生生的版本在这里:
https://github.com/keen99/shell-functions/tree/master/resolve_path
但出于这样的目的,这是当前版本(我觉得它经过了很好的测试......但我愿意接受反馈!)
让它适用于普通的 bourne shell (sh) 可能并不困难,但我没有尝试......我太喜欢 $FUNCNAME 了。:)
#!/bin/bash
resolve_path() {
#I'm bash only, please!
# usage: resolve_path <a file or directory>
# follows symlinks and relative paths, returns a full real path
#
local owd="$PWD"
#echo "$FUNCNAME for $1" >&2
local opath="$1"
local npath=""
local obase=$(basename "$opath")
local odir=$(dirname "$opath")
if [[ -L "$opath" ]]
then
#it's a link.
#file or directory, we want to cd into it's dir
cd $odir
#then extract where the link points.
npath=$(readlink "$obase")
#have to -L BEFORE we -f, because -f includes -L :(
if [[ -L $npath ]]
then
#the link points to another symlink, so go follow that.
resolve_path "$npath"
#and finish out early, we're done.
return $?
#done
elif [[ -f $npath ]]
#the link points to a file.
then
#get the dir for the new file
nbase=$(basename $npath)
npath=$(dirname $npath)
cd "$npath"
ndir=$(pwd -P)
retval=0
#done
elif [[ -d $npath ]]
then
#the link points to a directory.
cd "$npath"
ndir=$(pwd -P)
retval=0
#done
else
echo "$FUNCNAME: ERROR: unknown condition inside link!!" >&2
echo "opath [[ $opath ]]" >&2
echo "npath [[ $npath ]]" >&2
return 1
fi
else
if ! [[ -e "$opath" ]]
then
echo "$FUNCNAME: $opath: No such file or directory" >&2
return 1
#and break early
elif [[ -d "$opath" ]]
then
cd "$opath"
ndir=$(pwd -P)
retval=0
#done
elif [[ -f "$opath" ]]
then
cd $odir
ndir=$(pwd -P)
nbase=$(basename "$opath")
retval=0
#done
else
echo "$FUNCNAME: ERROR: unknown condition outside link!!" >&2
echo "opath [[ $opath ]]" >&2
return 1
fi
fi
#now assemble our output
echo -n "$ndir"
if [[ "x${nbase:=}" != "x" ]]
then
echo "/$nbase"
else
echo
fi
#now return to where we were
cd "$owd"
return $retval
}
这是一个经典的例子,感谢brew:
%% ls -l `which mvn`
lrwxr-xr-x 1 draistrick 502 29 Dec 17 10:50 /usr/local/bin/mvn@ -> ../Cellar/maven/3.2.3/bin/mvn
使用此函数,它将返回 -real- 路径:
%% cat test.sh
#!/bin/bash
. resolve_path.inc
echo
echo "relative symlinked path:"
which mvn
echo
echo "and the real path:"
resolve_path `which mvn`
%% test.sh
relative symlinked path:
/usr/local/bin/mvn
and the real path:
/usr/local/Cellar/maven/3.2.3/libexec/bin/mvn
为了解决 Mac 不兼容的问题,我想出了
echo `php -r "echo realpath('foo');"`
不是很好,但跨操作系统
以下是如何使用内联 Perl 脚本获取 MacOS/Unix 中文件的实际路径:
FILE=$(perl -e "use Cwd qw(abs_path); print abs_path('$0')")
同样,要获取符号链接文件的目录:
DIR=$(perl -e "use Cwd qw(abs_path); use File::Basename; print dirname(abs_path('$0'))")
您的路径是目录还是文件?如果它是一个目录,那就很简单:
(cd "$DIR"; pwd -P)
但是,如果它可能是一个文件,那么这将不起作用:
DIR=$(cd $(dirname "$FILE"); pwd -P); echo "${DIR}/$(readlink "$FILE")"
因为符号链接可能解析为相对路径或完整路径。
在脚本上,我需要找到真实路径,以便我可以引用配置或与其一起安装的其他脚本,我使用以下命令:
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
SOURCE="$(readlink "$SOURCE")"
[[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
你可以设置 SOURCE
到任何文件路径。基本上,只要路径是符号链接,它就会解析该符号链接。诀窍在于循环的最后一行。如果解析的符号链接是绝对的,它将使用它作为 SOURCE
. 。但是,如果它是相对的,它将预先添加 DIR
对于它,通过我首先描述的简单技巧将其解析为真实位置。
我相信这是真正且明确的“解析符号链接的方法”,无论它是目录还是非目录,使用 Bash:
function readlinks {(
set -o errexit -o nounset
declare n=0 limit=1024 link="$1"
# If it's a directory, just skip all this.
if cd "$link" 2>/dev/null
then
pwd -P "$link"
return 0
fi
# Resolve until we are out of links (or recurse too deep).
while [[ -L $link ]] && [[ $n -lt $limit ]]
do
cd "$(dirname -- "$link")"
n=$((n + 1))
link="$(readlink -- "${link##*/}")"
done
cd "$(dirname -- "$link")"
if [[ $n -ge $limit ]]
then
echo "Recursion limit ($limit) exceeded." >&2
return 2
fi
printf '%s/%s\n' "$(pwd -P)" "${link##*/}"
)}
请注意,所有 cd
和 set
事情发生在子外壳中。
在这里,我提出了一个我认为是跨平台(至少是 Linux 和 macOS)的解决方案,目前对我来说效果很好。
crosspath()
{
local ref="$1"
if [ -x "$(which realpath)" ]; then
path="$(realpath "$ref")"
else
path="$(readlink -f "$ref" 2> /dev/null)"
if [ $? -gt 0 ]; then
if [ -x "$(which readlink)" ]; then
if [ ! -z "$(readlink "$ref")" ]; then
ref="$(readlink "$ref")"
fi
else
echo "realpath and readlink not available. The following may not be the final path." 1>&2
fi
if [ -d "$ref" ]; then
path="$(cd "$ref"; pwd -P)"
else
path="$(cd $(dirname "$ref"); pwd -P)/$(basename "$ref")"
fi
fi
fi
echo "$path"
}
这是一个 macOS(仅?)解决方案。可能更适合原来的问题。
mac_realpath()
{
local ref="$1"
if [[ ! -z "$(readlink "$ref")" ]]; then
ref="$(readlink "$1")"
fi
if [[ -d "$ref" ]]; then
echo "$(cd "$ref"; pwd -P)"
else
echo "$(cd $(dirname "$ref"); pwd -P)/$(basename "$ref")"
fi
}