如何在OS X上使用CLI在文件或目录上设置图标?

Gre*_*cic 5 macos icons command-line-interface

使用Finder中的"获取信息"对话框可以直接在文件或目录上设置图标.

  1. 从例如预览中复制图像
  2. 在文件或目录上打开"获取信息"
  3. 按Tab键选择图标
  4. 粘贴Cmd-V

但是如何使用命令行执行此操作?

Gre*_*cic 7

这是一个bash脚本"setIcon.sh"

#!/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
Run Code Online (Sandbox Code Playgroud)

  • Rez 和 SetFile 在其手册页中被标记为已弃用。有没有不推荐的方法来做到这一点? (2认同)