繁体   English   中英

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

[英]OS X terminal command to resolve path of an alias

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

我有这个问题,所以我实现了一个命令行工具。 它是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];

我找到了以下脚本,它可以满足我的需求:

#!/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

我找到了这个工具

一小段编译代码, .bash_profile的函数,以及瞧。 透明处理别名,只需使用“cd”。 比使用Applescript快几倍。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM