2009-07-23 125 views
6

我正在寫一個shell腳本,它將rsync文件從遠程機器,一些linux,一些macs,到一箇中央備份服務器。 Mac的根級別上有文件夾,其中包含需要備份的所有文件/文件夾的別名。我可以使用什麼終端命令來解析別名指向的文件/文件夾的路徑? (我需要這些路徑傳遞到rsync的)OS X終端命令解析別名的路徑

回答

3

我發現下面的腳本,做什麼,我需要:

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

只要能夠在腳本運行時訪問原始項目,這就好了。如果別名損壞或無法裝入卷,則不起作用。我已經添加鏈接到一個工具,可以在這些情況下工作在另一個答案http://stackoverflow.com/a/17570232/425078 – rptb1 2013-07-10 12:07:29

+0

爲什麼所有複製和恢復現有的fd 2?爲什麼不說`path = $(osascript 2>/dev/null << EOF ...)` – dubiousjim 2015-08-31 18:39:31

3

我發現this tool

一小部分編譯代碼,.bash_profile中的一個函數,以及瞧。透明處理別名,只需使用「cd」即可。也比使用Applescript快幾倍。

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];