在Finder中使用“获取信息”对话框设置文件或目录上的图标非常简单。
- 从预览等应用程序中复制图像
- 打开文件或目录上的“获取信息”
- 按TAB键选择图标
- 粘贴Cmd-V
但是如何使用命令行完成此操作呢?
在Finder中使用“获取信息”对话框设置文件或目录上的图标非常简单。
但是如何使用命令行完成此操作呢?
这里有一个名为 "setIcon.sh" 的bash脚本可以用来实现
#!/bin/sh
# Sets an icon on file or directory
# Usage setIcon.sh iconimage.jpg /path/to/[file|folder]
iconSource=$1
iconDestination=$2
icon=/tmp/`basename $iconSource`
rsrc=/tmp/icon.rsrc
# Create icon from the iconSource
cp $iconSource $icon
# Add icon to image file, meaning use itself as the icon
sips -i $icon
# Take that icon and put it into a rsrc file
DeRez -only icns $icon > $rsrc
# Apply the rsrc file to
SetFile -a C $iconDestination
if [ -f $iconDestination ]; then
# Destination is a file
Rez -append $rsrc -o $iconDestination
elif [ -d $iconDestination ]; then
# Destination is a directory
# Create the magical Icon\r file
touch $iconDestination/$'Icon\r'
Rez -append $rsrc -o $iconDestination/Icon?
SetFile -a V $iconDestination/Icon?
fi
# Sometimes Finder needs to be reactivated
#osascript -e 'tell application "Finder" to quit'
#osascript -e 'delay 2'
#osascript -e 'tell application "Finder" to activate'
rm $rsrc $icon
Icon$'\r'
。您必须将其指定为$'Icon\r'
。无论如何,任何引用或转义都无法使bash/zsh满意。 - MushyMiddle$ echo "read 'icns' (-16455) \"Icon.icns\";" >> Icon.rsrc
$ Rez -a Icon.rsrc -o FileName.ext
$ SetFile -a C FileName.ext
$ Rez -a Icon.rsrc -o Icon$'\r'
$ SetFile -a C .
将魔法图标文件隐藏在当前文件夹中(按⇧⌘.在Finder中显示/隐藏隐藏文件):
$ SetFile -a V Icon$'\r'
图标数据存储在扩展属性"com.apple.ResourceFork"的值中(在终端中输入命令"xattr -p com.apple.ResourceFork FileName.ext"以打印该值)。对于文件夹,文件夹内部有一个神奇的(无内容且隐藏的)文件Icon$'\r'
。要从扩展属性"com.apple.ResourceFork"中提取图标数据并转换为纯文本资源文件(从中我们可以知道正确的icns类型标识符"-16455"):
$ DeRez -only icns FileWithIcon.ext > Icon.rsrc
$ DeRez -only icns /Folder/With/Icon/Icon$'\r' > Icon.rsrc
$ sips -i ImageFile.icns/png/jpg
会生成错误--addIcon is no longer supported
。开关-i
表示将"com.apple.ResourceFork"扩展属性作为"--addIcon"附加到该文件本身上,使用此图像文件的内容。