LoginSignup
16
18

More than 5 years have passed since last update.

OSXで使えるAppleScriptを使ったコマンド集

Last updated at Posted at 2015-11-12

はじめに

~/.bashrc~/.zshrc に追記してお使いください。
当方Yosemiteにて動作確認してます。(El Capitan に早いとこ上げたい…)

いいネタがあれば後から追加していく予定です。コメント欄でも是非紹介してください。

テクニック

引数の参照

一番オーソドックスな方法です。

on run argv
    log item N of argv
end run
osascript -e '
    on run argv
        log "Hello, " & item 1 of argv & "."
    end run
' "$variable"

環境変数の参照

以下のシンタックスで利用出来るはずなんですが、手元では全く動作確認出来なかったのでこれは見送ります。

system attribute "ATTRIBUTE_NAME"

埋め込む文字列のエスケープ

引数として渡せない事情がある場合はこちらを採用します。

ダブルクオートリテラルの作成: "string"

AppleScriptでは文字列リテラルにダブルクオートしか使えません。
変数の置換機能では限界があるのでPerlを利用します。
またbashとzshでechoの挙動が違うので、-Eでbashに合わせます。

variable='"'$(echo -E "$variable" | perl -pe 's/(?=[\\"])/\\/g')'"'

スクリーンショット 2015-11-16 1.35.19.png

(参考) PHPのようにドル記号を解釈する言語向けのエスケープ
variable='"'$(echo -E "$variable" | perl -pe 's/(?=[\\"\$])/\\/g')'"'

シングルクオートリテラルの作成: 'string'

今回は使えませんが、参考までにこちらも掲載しておきます。

variable="'"$(echo -E "$variable" | perl -pe "s/'/'\"'\"'/g")"'"

フルパスの取得

AppleScriptではファイル名を指定するとき相対パスを受け付けてくれません。
OSXにはrealpathが無いのでPerlを利用することになります。

# 単一引数
perl -MCwd -e 'print Cwd::abs_path(shift)' "$variable"
# 複数引数
perl -MCwd -e 'print Cwd::abs_path($_) for @ARGV' "$variable"
使用例
example@localhost:/bin$ variable='bash'
example@localhost:/bin$ perl -MCwd -e 'print Cwd::abs_path(shift)' "$variable"
/bin/bash

コマンド

ターミナルプロファイルの変更

termprf() {
    osascript -e '
        on run argv
            if exists (window 1 of application "Terminal") then
                tell application "Terminal"
                    set current settings of window 1 to settings set (item 1 of argv)
                end tell
            end if
        end run
    ' "$1"
}
使用例
example@localhost:~$ termprf homebrew

壁紙の変更

chwall() {
    osascript -e '
        on run argv
            tell application "Finder" to set desktop picture to POSIX file (item 1 of argv)
        end run
    ' "$(perl -MCwd -e 'print Cwd::abs_path(shift)' "$1")"
}
使用例
example@localhost:~/Pictures/淫夢$ chwall ご満悦先輩.png
16
18
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
18