在Mac OS X Finder中,可以给文件和文件夹打上颜色标签。 是否有一种方法可以通过shell脚本实现这一点?
在Mac OS X Finder中,可以给文件和文件夹打上颜色标签。 是否有一种方法可以通过shell脚本实现这一点?
这个 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变量,而$label是一个标签索引号的shell变量,
osascript -e "tell application \"Finder\" to set label index of alias POSIX file \"$filename\" to $label"
是一个用于给文件或文件夹赋予标签的 shell 命令。
osascript
(即,osascript -e <script> <arg>
),然后在脚本内部使用on run theArguments ... end run
处理程序来检索它们。 - Kevin Reid这是我编写的一个Python脚本:
https://github.com/danthedeckie/finder_colors
它可以通过命令行设置文件夹和文件的颜色。
使用方法:
finder_colors.py red /Users/daniel/src
将/Users/daniel/src目录设置为红色。
finder_colors.py /Users/daniel/src
返回颜色(在此情况下为“红色”)。如果您正在编写Python脚本,可以将finder_colors作为模块导入并直接使用它(finder_colors.get(...)和finder_colors.set(...))。
根据这里和相关帖子的回复,我制作了以下函数并将其添加到了我的~/.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 - "$@" << 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
}
一种丑陋的方法是:
exec osascript <<\EOF
tell app "Finder"
-- [...]
-- selecting the file
-- [...]
-- 4 is Blue
set label index of thisItem to 4
end tell
这将使用与Finder相同的颜色顺序。
#!/bin/bash
if [[ $# -le 1 || ! "$1" =~ ^[0-7]$ ]]; then
echo "Usage: label 01234567 file ..." 1>&2
exit 1
fi
colors=( 0 2 1 3 6 4 5 7 )
n=${colors[$1]}
shift
osascript - "$@" <<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