OS X终端命令以解析别名的路径

10

我正在编写一个shell脚本,它将从一些Linux和Mac的远程机器上同步文件到一个中央备份服务器。在根目录下,Mac有包含所有需要备份的文件/文件夹的别名文件夹。有什么终端命令可以解析别名指向的文件/文件夹的路径?(我需要将这些路径传递给rsync)

3个回答

10

我曾经遇到这个问题,所以我开发了一个命令行工具。它是开源的,网址是https://github.com/rptb1/aliasPath

关键在于即使别名损坏,它也能正常工作,这点不同于我找到的所有AppleScript解决方案。因此,您可以使用它编写脚本来修复大量文件更改卷时遇到的别名问题。这就是我为什么编写它的原因。

源代码非常简短,但以下是其关键部分的摘要,供任何需要使用代码解决此问题或想查找相关协议的人使用。

NSString *aliasPath = [NSString stringWithUTF8String:posixPathToAlias];
NSURL *aliasURL = [NSURL fileURLWithPath:aliasPath];
NSError *error;
NSData *bookmarkData = [NSURL bookmarkDataWithContentsOfURL:aliasURL error:&error];
NSDictionary *values = [NSURL resourceValuesForKeys:@[NSURLPathKey]
                                   fromBookmarkData:bookmarkData];
NSString *path = [values objectForKey:NSURLPathKey];
const char *s = [path UTF8String];

7
我找到了下面的脚本,它可以完成我需要的功能:
#!/bin/sh
if [ $# -eq 0 ]; then
  echo ""
  echo "Usage: $0 alias"
  echo "  where alias is an alias file."
  echo "  Returns the file path to the original file referenced by a"
  echo "  Mac OS X GUI alias.  Use it to execute commands on the"
  echo "  referenced file.  For example, if aliasd is an alias of"
  echo "  a directory, entering"
  echo '   % cd `apath aliasd`'
  echo "  at the command line prompt would change the working directory"
  echo "  to the original directory."
  echo ""
fi
if [ -f "$1" -a ! -L "$1" ]; then
    # Redirect stderr to dev null to suppress OSA environment errors
    exec 6>&2 # Link file descriptor 6 with stderr so we can restore stderr later
    exec 2>/dev/null # stderr replaced by /dev/null
    path=$(osascript << EOF
tell application "Finder"
set theItem to (POSIX file "${1}") as alias
if the kind of theItem is "alias" then
get the posix path of ((original item of theItem) as text)
end if
end tell
EOF
)
    exec 2>&6 6>&-      # Restore stderr and close file descriptor #6.

    echo "$path"
fi

只要在脚本运行时可以访问到原始项,这就没问题。如果别名失效或卷无法挂载,则无法使用。我已在另一个答案中添加了一个可以在这些情况下工作的工具链接https://dev59.com/6kjSa4cB1Zd3GeqPGZLa#17570232。 - rptb1
为什么要复制和恢复现有的fd 2?为什么不直接说path=$(osascript 2>/dev/null << EOF ...) - dubiousjim
@dubiousjim 那样会更简洁。这个脚本不是我写的,我是在网上找到的。话虽如此,我会测试你的建议并更新答案。 - Josh
@Josh,如果这个脚本不是你自己编写的,那么你至少应该包含一个指向它来源的链接。 - user82216

3

我找到了这个工具

只需要在你的.bash_profile中添加一小段编译代码,就可以实现透明处理别名,只需使用"cd"命令即可。速度比使用Applescript快几倍。


你链接中有用的部分(这个工具):getTrueName.c已经无法从那里获取了。 - dan
1
@danielAzuelos 谢谢您告诉我!我已经在推特上联系了作者,链接已经修复。 - Groxx
链接又坏了,但相关的脚本 getTrueName.c 几乎肯定是 这个答案 中提供的那个,该答案又指回了这个源 - Karl der Kaefer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接