如何解决在shell脚本的符号链接 [英] How to resolve symbolic links in a shell script

查看:168
本文介绍了如何解决在shell脚本的符号链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个绝对或相对路径(在类Unix系统),我想确定解决任何中间的符号链接后目标的完整路径。加分也同时解决〜用户名符号。

Given an absolute or relative path (in a Unix-like system), I would like to determine the full path of the target after resolving any intermediate symlinks. Bonus points for also resolving ~username notation at the same time.

如果目标是一个目录,它可能是可能的chdir()到该目录中,然后调用GETCWD(),但我真的想从一个shell脚本做到这一点,而不是写一个C帮手。不幸的是,炮弹都尝试从用户隐藏符号链接的存在(这是bash的在OS X)的倾向:

If the target is a directory, it might be possible to chdir() into the directory and then call getcwd(), but I really want to do this from a shell script rather than writing a C helper. Unfortunately, shells have a tendency to try to hide the existence of symlinks from the user (this is bash on OS X):

$ 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
$

我要的是一个函数解析(),使得在上面的例子中从tmp目录执行时,解决(富)==/用户/格雷格的/ tmp /条。

What I want is a function resolve() such that when executed from the tmp directory in the above example, resolve("foo") == "/Users/greg/tmp/bar".

推荐答案

根据标准, PWD -P 应返回与解决符号链接的路径。

According to the standards, pwd -P should return the path with symlinks resolved.

C函数的char * GETCWD(的char * buf中,为size_t大小) unistd.h中应具有相同的行为。

C function char *getcwd(char *buf, size_t size) from unistd.h should have the same behaviour.

GETCWD
PWD

这篇关于如何解决在shell脚本的符号链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆