1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ラズパイの初回起動時にカスタムスクリプトを実行する方法

Posted at

はじめに

ラズパイの初回起動時に自動でスクリプトを実行できる方法がないかと思い,調査を行いました.systemdのサービスファイルを作って,自動起動するという記事は多くあるのですが,その方法では一度手動でラズパイ上での設定が必要になってしまいます.

Pi Imagerでsshやwifiの設定を行えるのですが,ここで設定をするとsdカードをラズパイにインストールし電源を入れるだけで全て設定が行われます.ここに秘密があるのでしょうということで,Pi Imagerで設定をしない場合とした場合で何が違うのか比べてみます.

自動実行方法の調査

何も設定しない状態でのSDカードのファイル構成
スクリーンショット 2025-03-19 18.26.54.png

Pi Imagerで設定した場合のファイル構成
スクリーンショット 2025-03-19 18.12.10.png
firstrun.shが増えていることがわかります.また,cmdline.txtの内容も変更されています.
何も設定していない場合のcmdline.txtはこちらですが

cmdline.txt(default)
console=serial0,115200 console=tty1 root=PARTUUID=194375f9-02 rootfstype=ext4 fsck.repair=yes rootwait quiet init=/usr/lib/raspberrypi-sys-mods/firstboot

設定をした場合は後ろに以下の文が追記されています.

systemd.run=/boot/firstrun.sh systemd.run_success_action=reboot systemd.unit=kernel-command-line.target

全体ではこのようになります.

cmdline.txt(configured)
console=serial0,115200 console=tty1 root=PARTUUID=194375f9-02 rootfstype=ext4 fsck.repair=yes rootwait quiet init=/usr/lib/raspberrypi-sys-mods/firstboot systemd.run=/boot/firstrun.sh systemd.run_success_action=reboot systemd.unit=kernel-command-line.target

実行

行った調査をもとに,OSインストール後cmdline.txtに追記しfirstrun.shを配置してラズパイを起動してみます.
うまく実行されたかわかるように/boot直下にsuccessというファイルを作成するようにします.

firstrun.sh
#!/bin/sh
touch success

起動後SDカードの中身を見てみると,successというファイルが黄枠で囲っている部分に作成されていることがわかります.うまくいきました.
スクリーンショット 2025-03-20 18.43.46 2.jpg
ちなみに,cmdline.txtのsystemd.run=/boot/firstrun.shの部分に違う名前のスクリプトを指定しても動作しました.

Pi Imagerで生成されるfirstrun.shの内容は以下の記事に詳細がありました.

おまけ

cmdline.txtのパラメータの意味

  • console=serial0,115200 →serial0(UART)に115200のボーレートでログを出力
  • console=tty1 →メインコンソール(tty1)にログを出力
  • root=PARTUUID=194375f9-02 →ルートファイルシステムが格納されてるパーティションのUUID
  • rootfstype=ext4 →ルートファイルシステムのフォーマット形式
  • fsck.repair=yes →起動時にファイルシステムの自動修復を行う
  • rootwait →ルートデバイスが認識されるまで待機する
  • quiet →起動ログを詳細に表示しない,デバッグする時は消しておく
  • init=/usr/lib/raspberrypi-sys-mods/firstboot →最初に実行するプログラム
  • systemd.run=/boot/firstrun.sh →systemdでfirstrun.shを実行する
  • systemd.run_success_action=reboot →firstrun.sh実行後に再起動する
  • systemd.unit=kernel-command-line.target →起動時にカーネルコマンドラインユニットを使用する

その他参考ページ

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?