How can I programmatically change a file's icon?


To change those icons from the command line, you can use the following command:

gvfs-set-attribute -t string /path/to/your/file metadata::custom-icon file:///path/to/your/icon.png

You can use this command in a bash script according to your needs.

If you run the command and the icon does not change immediately, you can install the xautomation package with:

sudo apt-get install xautomation

And finally, use the command "xte" to "sendkey" in bash like "F5" to refresh..
A little example would be:

#!/bin/bash
gvfs-set-attribute -t string /home/hermes/testicon metadata::custom-icon file:///home/hermes/Desktop/applet_blank.png
sleep 3
xte "key F5"  

I hope this is useful for you.


gio (gnome > 3.xx)

Since gvfs tools are outdated, you should use gio instead!

The commands are very similar to the one described above.

For instance if you want to get information about the icon set use

gio info ~/path/to/your/dir/or/folder | awk '{/custom-icon/ print $2}' | cut -c8-

This outputs the full path to the icon, assumed you have made a custom-icon. To set an custom-icon simply use the command

gio set -t string /path/to/your/dir/or/folder metadata::custom-icon file:///path/to/your/icon.svg

Roman's answer looks ideal. There is another less elegant way. I'm not sure where icons live in the rest of the system, but icons that are on your Desktop are just little plain text files in $HOME/Desktop. They usually (but don't have to) have the extension of .desktop. One of the fields in these files is Icon=.... You can use a program to change whatever that field is set to to the value of your choice. (You may have to do a refresh after doing this just as Roman suggests.)

When I want to use an icon for something else or on another system, I sometimes look in these .desktop files to find out what the icon in use is named.

The specs for these files live at: http://www.freedesktop.org/wiki/Specifications/desktop-entry-spec

Joe