To set an icon on a file or directory is straight forward using the "Get Info" dialog in Finder.
- copy image from e.g. Preview
- open "Get Info" on file or directory
- press TAB to select the icon
- paste Cmd-V
But how do you do this using the command line?
Here is a bash script "setIcon.sh" for it
Assuming that we have icns-file already. Create temp resource file which points to icns-file:
Append the resource file as value of extended attribute "com.apple.ResourceFork" to a file:
Show the icon of the file:
Append resource file as value of extended attribute "com.apple.ResourceFork" to a magic icon file inside current folder:
Show the icon of current folder:
Hide the magic icon file inside current folder (press ⇧⌘. to show/hide hidden files in Finder):
Additional details
Icon data is stored as value of extended attribute "com.apple.ResourceFork" (Terminal command "xattr -p com.apple.ResourceFork FileName.ext" prints the value). For a folder there is magic (which is empty and hidden) file
Icon$'\r'
inside the folder. To extract icon data from extended attribute "com.apple.ResourceFork" into plain text resource file (from which we know correct icns-type identifier "-16455"):Under macOS 10.13 High Sierra command
$ sips -i ImageFile.icns/png/jpg
generates error--addIcon is no longer supported
. Switch-i
means "--addIcon" as extended attribute "com.apple.ResourceFork" onto this file itself using the content of this image file.