LoginSignup
11
5

More than 1 year has passed since last update.

macOS起動時にスクリプトを実行する

Posted at

やり方 (概略)

  1. スクリプト作成
  2. スクリプトをLaunchdに登録するための.plistを作成 (権限や配置に注意)
  3. .plistを読み込む

具体例

1.スクリプト作成

~/launch_scripts/hello/hello_shell.sh
echo hello_world

2. スクリプトをLaunchdに登録するためのplistを作成 (権限に注意)

  • .plistの配置場所は以下の通り
    • ~/Library/LaunchAgents
      • 各ユーザが管理する各ユーザユーザごとに実行するエージェントの格納ディレクトリ
    • /Library/LaunchAgents
      • 管理者が管理するする各ユーザごとに行するのエージェントの格納ディレクトリ
    • /Library/LaunchDaemons
      • 管理者が管理するシステムで実行するデーモンの格納ディレクトリ(ログイン状態に依らない)
    • /System/Library/LaunchAgents
      • OS が管理する各ユーザごとに実行するエージェントの格納ディレクトリ(基本的に触らない)
    • /System/Library/LaunchDaemons
      • OS が管理するシステムで実行するデーモンの格納ディレクトリ(基本的に触らない)
/Library/LaunchAgents/hello.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <!-- launchd プロセスで一意ならOK -->
    <key>Label</key>
    <string>com.example.hello</string>

    <!-- 実行するコマンド -->
    <key>ProgramArguments</key>
    <array>
        <!-- ~が使えないことに注意 -->
        <string>/Users/ritumutaka/launch_scripts/hello/hello.sh</string>
        <string>引数1</string>
        <string>引数2</string>
    </array>

    <!-- launchd を読み込んだタイミングで実行 -->
    <key>RunAtLoad</key>
    <true/>

    <!-- ログ保存用 -->
    <key>StandardOutPath</key>
    <string>/Users/ritumutaka/launch_scripts/hello/std_out.txt</string>
    <key>StandardErrorPath</key>
    <string>/Users/ritumutaka/launch_scripts/hello/std_err.txt</string>
</dict>
</plist>
  • hello.plistのシンタックスエラーをチェック
    • $ plutil -lint hello.plist
  • 問題なければ以下のように出力される
    • hello.plist: OK

3. plistを読み込む

  • 読み込みコマンド (実際にスクリプトが実行される)
    • $ launchctl load ~/Library/LaunchAgents/hello.plist
  • テストしたい場合、再ロードすれば良い
    • $ launchctl unload ~/Library/LaunchAgents/hello.plist
    • $ launchctl load ~/Library/LaunchAgents/hello.plist

管理者権限で実行する場合

  • 所有者、権限、配置を確認

    • $ cd /Library/LaunchDaemons
    • $ ls -l
    • ダメな例: -rw-rw-r--@ 1 ritumutaka staff 843 6 26 18:05 hello.plist
    • 良い例: -rw-r--r--@ 1 root staff 843 6 26 18:05 hello.plist
  • .plistファイルの所有者をrootにする

    • $ sudo chown root /Library/LaunchDaemons/hello.plist
  • 権限は「-rw-r--r--」 (644)

    • $ sudo chmod 644 hello.plist
  • テスト時はsudo付きでロード

    • $ sudo launchctl load ~/Library/LaunchAgents/hello.plist

Load failed: 5: Input/Output error

  • ファイルの所有権
    • 管理者権限で実行する場合はroot、ユーザー実行なら対象ユーザー
  • 権限
    • 管理者権限なら「644」、ユーザー実行なら「664」
  • unloadかけてない
    • 再ロードする場合はちゃんと以下の順番で行うこと
      • $ launchctl unload
      • $ launchctl load
11
5
0

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
11
5