🔔

macOSでコマンドから通知を出す

に公開

環境: macOS Sequoia 15.5

初期設定

検索すれば osascript コマンドで display notification すればよいという情報が得られるが、なぜか正常終了だけして通知が出ない!!!

同じ症状の人がいて、一度Script Editorから通知を出すとうまくいくという情報が得られました。

Script Editorでdisplay notification "Hello" with title "Hi" とかしてやって、システム設定(通知)でScript Editorの通知を有効にしたところ、osascriptコマンドからも通知を発行できるようになりました。良かったですね。

osascriptコマンドで通知を出す

さて、通知を出すには、 display notification {本文} with title {タイトル} としてやればよい。

osascript -e 'display notification "Lorem ipsum dolor sit amet" with title "Title"'

引数で通知内容を指定する

on run argv
  display notification (item 1 of argv as text) with title "通知"
end run

というスクリプトを実行すれば、第一引数を通知内容に指定できる。

ところで osascriptで複数行のスクリプトを入力するには -e を複数指定するというテクがあり、このように書けます:

osascript -e 'on run argv' -e 'display notification (item 1 of argv as text)' -e 'end run' Hello

標準入力から通知内容を読む

osascript -e 'on run argv' -e 'display notification (item 1 of argv as text)' -e 'end run' "$(cat)"

などとすればよいでしょう。

Claude CodeのNotificationイベント用

STDINから{"message": string, "title": string}を読んで通知を出す

jq -j '.message, "\u0000", .title // "Claude Code", "\u0000"' | xargs -0 osascript -e 'on run argv' -e 'display notification (item 1 of argv as text) with title (item 2 of argv as text)' -e 'end run'

Claude CodeのStopイベント用

対応するメッセージをログから読んで通知を出す

osascript -e 'on run argv' -e 'display notification (item 1 of argv as text) with title "Claude Code"' -e 'end run' "$(jq -r '.transcript_path' | xargs tail -n 1 | jq -r '.message.content[0].text // "Completed"')"

Discussion