You can use xattr. This copies the tags from file1 to file2:
xattr -wx com.apple.metadata:_kMDItemUserTags "$(xattr -px com.apple.metadata:_kMDItemUserTags file1)" file2
xattr -wx com.apple.FinderInfo "$(xattr -px com.apple.FinderInfo file1)" file2
The tags are stored in a property list as a single array of strings:
$ xattr -p com.apple.metadata:_kMDItemUserTags file3|xxd -r -p|plutil -convert xml1 - -o -
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
<string>Red
6</string>
<string>aa</string>
<string>Orange
7</string>
<string>Yellow
5</string>
<string>Green
2</string>
<string>Blue
4</string>
<string>Purple
3</string>
<string>Gray
1</string>
</array>
</plist>
The tags for colors have values like Red\n6
(where \n
is a linefeed).
If the kColor flag in com.apple.FinderInfo is unset, Finder doesn't show the circles for colors next to files. If the kColor flag is set to orange and the file has the red tag, Finder shows both red and orange circles. You can set the kColor flag with AppleScript:
do shell script "xattr -w com.apple.metadata:_kMDItemUserTags '(\"Red\\n6\",\"new tag\")' ~/desktop/file4"
tell application "Finder" to set label index of file "file4" of desktop to item 1 of {2, 1, 3, 6, 4, 5, 7}
'("Red\n6","new tag")'
is old-style plist syntax for this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
<string>Red
6</string>
<string>new tag</string>
</array>
</plist>
xattr -p com.apple.FinderInfo file|head -n1|cut -c28-29
prints the value of the bits used for the kColor flag. Red is C, orange is E, yellow is A, green is 4, blue is 8, magenta is 6, and gray is 2. (The flag that would add 1 to the values is not used in OS X.)