2010-03-12 56 views

回答

8

這個shell腳本需要的文件或文件夾的名稱作爲其第一個參數,標籤指數(0沒有標籤,1代表紅色,...,7代表灰色)作爲第二個參數。

#!/bin/sh 
osascript -e "tell application \"Finder\" to set label index of alias POSIX file \"`cd -P -- "$(dirname -- "$1")" && printf '%s\n' "$(pwd -P)/$(basename -- "$1")"`\" to $2" 

更直接地,如果$ filename是與該文件或文件夾的絕對路徑名shell變量將被標記和$標籤和該標籤索引號shell變量,

osascript -e "tell application \"Finder\" to set label index of alias POSIX file \"$filename\" to $label" 

是將標籤分配給文件或文件夾的shell命令。

+0

如果文件名包含雙引號或以反斜槓結尾。 – 2010-03-14 00:27:34

+0

@Kevin:任何解決方案? – Svish 2010-07-28 18:37:18

+0

@Kevin:另外...爲什麼你會有一個包含雙引號的文件名?我認爲這是無效的...或者只是在Windows中...... – Svish 2010-07-28 18:43:38

4

基於這裏的答覆,並在引用的文章中,我提出了以下功能並將其添加到我的~/.bash_profile文件:

# Set Finder label color 
label(){ 
    if [ $# -lt 2 ]; then 
    echo "USAGE: label [0-7] file1 [file2] ..." 
    echo "Sets the Finder label (color) for files" 
    echo "Default colors:" 
    echo " 0 No color" 
    echo " 1 Orange" 
    echo " 2 Red" 
    echo " 3 Yellow" 
    echo " 4 Blue" 
    echo " 5 Purple" 
    echo " 6 Green" 
    echo " 7 Gray" 
    else 
    osascript - "[email protected]" << EOF 
    on run argv 
     set labelIndex to (item 1 of argv as number) 
     repeat with i from 2 to (count of argv) 
      tell application "Finder" 
       set theFile to POSIX file (item i of argv) as alias 
       set label index of theFile to labelIndex 
      end tell 
     end repeat 
    end run 
EOF 
    fi 
} 
1

還有在osxutils包中的命令行工具「setlabel」。它不需要AppleScript或Finder正在運行。

0

這將使用與Finder相同的顏色順序。

#!/bin/bash 

if [[ $# -le 1 || ! "$1" =~ ^[0-7]$ ]]; then 
    echo "Usage: labelfile ..." 1>&2 
    exit 1 
fi 

colors=(0 2 1 3 6 4 5 7) 
n=${colors[$1]} 
shift 

osascript - "[email protected]" <<END > /dev/null 2>&1 
on run arguments 
tell application "Finder" 
repeat with f in arguments 
set f to (posix file (contents of f) as alias) 
set label index of f to $n 
end repeat 
end tell 
end 
END 

我重定向STDERR,因爲我在10.8有像2012-09-06 13:50:00.965 osascript[45254:707] CFURLGetFSRef was passed this URL which has no scheme (the URL may not work with other CFURL routines): test.txt警告。 STDOUT被重定向,因爲osascript輸出最後一個表達式的值。

8

這裏有一個快速的Python腳本我寫道:

https://github.com/danthedeckie/finder_colors

這臺從命令行文件夾和文件的顏色。

用法:

finder_colors.py red /Users/daniel/src 

設置/用戶/丹尼爾/ src目錄是紅色。

finder_colors.py /Users/daniel/src 

返回顏色(在本例中爲'紅')。如果您正在編寫python腳本,則可以將finder_colors作爲模塊導入,並直接使用它(finder_colors.get(...)和finder_colors.set(...)。

+0

如果你解釋你是如何做的話,例如通過你的解決方案的相關代碼示例,將會對你有所幫助。 – Pfitz 2012-10-09 14:58:19

+0

Thanks @Pfitz - I've added使用信息,它在內部工作的方式是使用內置的python庫來編輯文件的擴展屬性 我找不到一個優雅的本地shell腳本方式來執行此操作,並且不喜歡Apple-腳本解決方案 – Daniel 2012-11-06 15:53:46

相關問題