Top / AppleScript

ターミナル (Terminal) Scripts

Mac OS Xでは、ユーティリティフォルダにあるターミナル (Terminal) などを使って、コマンドラインでソフトウェアを扱えるようになりましたね。

●ドロップしたファイルをターミナルに渡し、指定したプログラムで処理

ターミナルのウィンドウにファイルをドラッグ&ドロップして、そのファイルのパスを入力させることもできますが、コマンドを打ち込むのを自動化してドラッグ&ドロップしたら一気に処理したい場合もあると思います。下のアップルスクリプトは、ドロップレットでないコマンドタイプ (GUIタイプでない) のプログラムの代わりに、ファイルを受け取り、自動的にコマンドを生成してターミナルのウィンドウに入力します。

このスクリプトは、アプリケーション形式でcrunch.appとかいった名前 (別に適当な名前でいい) で保存して、同じフォルダ (ディレクトリ階層) に処理するプログラム (ここではcrunch.plxという名前のPerlスクリプト) があるとしています。binなどという名前のサブフォルダにプログラムを入れるなら、プログラムのパスを指定しているところにbin/あるいはbin:を補ってやればいいでしょう。このAppleScriptアプリケーションのファイルをダブルクリックすると、処理するプログラム (テキスト) を開くようにしていますが、ファイルを引数に必要としないプログラムなんかであれば、それを実行するようにするといいでしょう (そうすると、このAppleScriptアプリケーションはプログラムのランチャー、ラッパーということになりますね)。

on open theItemsDropped
    set theItems to ""
    repeat with aFile in theItemsDropped
        set theItems to theItems & space & quoted form of POSIX path of aFile
    end repeat
    set myPath to POSIX path of (path to me) -- このAppleScriptアプリケーションのパス
    set curPath to text 1 thru -(offset of "/" in (reverse of characters of myPath) as string) of myPath
    -- curPathはこのAppleScriptアプリケーションのあるフォルダのパス
    set progPath to curPath & "crunch.plx" -- 処理するプログラムを指定
    set theCommand to "perl " & (quoted form of progPath) & theItems
    -- do shell script theCommand
    -- set theResult to do shell script theCommand -- 出力を得る
    -- delay 3などとしてタイミングを調整した方がいいかもしれない
    tell application "Terminal"
        activate
        if not (exists front window) then do script ""
        do script theCommand in front window
    end tell
end open

on run -- ダブルクリックしたら、処理するプログラムを編集したいのだと判断して開く
    set myPath to (path to me) as string -- このAppleScriptアプリケーションのパス
    -- curPathはこのAppleScriptアプリケーションのあるフォルダのパス
    set curPath to text 1 thru -(offset of ":" in (reverse of characters of myPath) as string) of myPath
    set progPath to curPath & "crunch.plx" -- 処理するプログラムを指定
    tell application "Jedit4" -- お好みのテキストエディタに (クリエータみたいなものか)
        activate
        open file progPath
    end tell
end run

実際はTerminalに出力を表示させるより、set theResult to do shell script theCommandなどとして出力を得て、好みのテキストエディタ等に表示させた方が便利かもしれません。具体的には、上のスクリプトでset theResult to do shell script theCommandのところをアンコメント (コメントでなく) して、tell application "Terminal"からend tellのブロックを、例えば下のようにするといいでしょう。

tell application "mi"
    activate
    if not (exists front document) then make new document
    if content of front document is not "" then make new document
    set content of front document to theResult
end tell

Top / AppleScript