Changing Dolphin’s directory icons in KDE5 via the command line

Recently I was interested in programmatically changing the icon of a specific directory in KDE’s default file manager Dolphin. Why would I need that? Well this can be handy, if you want to dynamically adapt the colors of a directory icon given certain situations: Maybe a file quota is exceeded, maybe you want to react to system events and reflect this by setting a specific icon for relevant directories.

Thankfully, KDE already offers such a helper tool by default: kwriteconfig5 enables you to modify KDE configuration files easily by passing the file name, the group and a key value pair. So to change an icon, simply update Dolphin’s .directory files like this:

kwriteconfig5 \
    --file ~/Documents/.directory \
    --group 'Desktop Entry' \
    --key 'Icon' 'folder-red'