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

Jos*_*osh 6 macos shell terminal path

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

rpt*_*tb1 7

我遇到了这个问题,所以我实现了一个命令行工具.它是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];
Run Code Online (Sandbox Code Playgroud)


Jos*_*osh 5

我发现以下脚本可以满足我的需求:

#!/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
Run Code Online (Sandbox Code Playgroud)