Set Bash Variable as Icon in osascript -e Display Dialog with icon

applescriptbashicon

I have a bash script that utilizes some osascript -e code for a dialog. I want to use a custom icon in that dialog. However, I don't understand how to code it so it's completely portable so as to make it executable no matter where a user may put it in his file system.


cd "$(dirname "$0")/../../"
CONTENTS="$PWD"
export ICNSPATH="$CONTENTS/Resources/path/to/icon/Myicon.icns"
osascript -e 'tell application id "com.apple.systemuiserver"' -e 'display dialog "Lorem ipsum dolor sit amet." buttons {"Cancel", "Okay"} with icon '$ICNSPATH' as alias' -e 'end tell'

Currently the only way I can get it to work with a custom icon is by hard coding it and I don't think it is a good idea.

Solutions should be w/o add-ons and must work on Mac OSes 10.6 – 10.10.

Appreciate any help you can render.

Best Answer

What always will work is encoding the icon file with base64 -b 64 (to keep the lines short enough), include it into your shell script as a here document and decode it on the fly.

To create a base64 encoded version of your icon file, run

base64 -b 64 -i path/to/icon/Myicon.icns > myicon.base64

(This you only need to do once).

Then open your shell script in your editor and insert myicon.base64 (which might be rather big) in the correct spot

...
ICNSPATH=${TMPDIR:-/tmp}/icon.$$.icns
base64 -D -o $ICNSPATH <<"END_OF_ICON"
** replace with content of myicon.base64 **
END_OF_ICON

osascript -e '... with icon '$ICNSPATH' as alias' # write full command here
rm -f $ICNSPATH

The final script will then look like the following

...
ICNSPATH=${TMPDIR:-/tmp}/icon.$$.icns
base64 -D -o $ICNSPATH <<"END_OF_ICON"
aG93IHRvIGNvZGUgaXQgc28gaXQncyBjb21wbGV0ZWx5IHBvcnRhYmxlIHNvIGFz
...
eSBwdXQgaXQgaW4gaGlzIGZpbGUgc3lzdGVtLgoK
END_OF_ICON

osascript -e '... with icon '$ICNSPATH' as alias'
rm -f $ICNSPATH