Mac OS X: How to change the color label of files from the Terminal

Based on the responses here and in referenced posts, I made the following function and added it to my ~/.bash_profile file:

# 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 - "$@" << 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
}
>

The osascript methods seemed broken for me in Mavericks AppleScript (and I haven't needed to try them since), but this works:

xattr -wx com.apple.FinderInfo \
 "0000000000000000000C00000000000000000000000000000000000000000000" \
 /path/to/your/file

(This marks the file as Red, you'll have to reverse-engineer other colours).

Under Mavericks this seems to merge the file label with the previous one (as they're now "tags").

In case it isn't obvious, this is Q&D and could break in the future, but it works (and is muuuch faster than AppleScript) in at least:

  • 10.9, HFS+
  • 11.6, APFS