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

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

问题描述

给定绝对或相对路径(在类 Unix 系统中),我想在解析任何中间符号链接后确定目标的完整路径.同时解析 ~username 符号的加分项.

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 帮助程序.不幸的是,shell 倾向于向用户隐藏符号链接的存在(这是 OS X 上的 bash):

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
$

我想要的是一个resolve()函数,当从上面例子中的tmp目录执行时,resolve("foo") == "/Users/greg/tmp/bar".

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 size) 来自 unistd.h 应该具有相同的行为.

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

getcwd密码

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

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