Skip to content

Instantly share code, notes, and snippets.

@inem
Last active May 16, 2017 08:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inem/fb1c4fd2dccb45a68f4f7bf745a84c91 to your computer and use it in GitHub Desktop.
Save inem/fb1c4fd2dccb45a68f4f7bf745a84c91 to your computer and use it in GitHub Desktop.
# Pure bash solution to lit, add and remove tags for files in OS X
# Based on https://apple.stackexchange.com/a/119370
# Depends on xattr (https://github.com/xattr/xattr - included in OS X?)
# Alternative: https://github.com/jdberry/tag
# Add the followingꜜ to your .bashrc
#tags <file>
#Lists all tags of a file
#tags -add <tag> <file>
#Adds tag to a file
#tags -remove <file>
#Removes all tags from a file
#TODO:
# - remove specific tag
tags() {
# tags system explained: http://arstechnica.com/apple/2013/10/os-x-10-9/9/
local src=$1
local action="get"
if [[ $src == "-remove" ]]; then
src=$2
local action="remove"
fi
if [[ $src == "-add" ]]; then
src=$3
local newtag=$2
local action="add"
fi
# hex -> bin -> json -> lines
local hexToLines="xxd -r -p - - | plutil -convert json -o - - | sed 's/[][]//g' | tr ',' '\n'"
# lines -> json -> bin -> hex
local linesToHex="tr '\n' ',' | echo [\$(sed 's/,$//')] | plutil -convert binary1 -o - - | xxd -p - -"
local gettags="xattr -px com.apple.metadata:_kMDItemUserTags \"$src\" 2> /dev/null | $hexToLines | sed 's/.*Property List error.*//'"
# echo $action
if [[ $action == "get" ]]; then
sh -c "$gettags"
elif [[ $action == "remove" ]]; then
local write="xattr -d com.apple.metadata:_kMDItemUserTags \"$src\""
sh -c "$write"
else
local add="(cat -; echo \\\"$newtag\\\") | sort -u"
local write="xattr -wx com.apple.metadata:_kMDItemUserTags \"\$($gettags | $add | grep . | $linesToHex)\" \"$src\""
sh -c "$write"
fi
}
export -f tags
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment