Table of Contents

Boot Time Scripts on FreeBSD

Sometimes you need to run a script at a specific point during the FreeBSD boot process. For example:

FreeBSD's rc(8) system makes this easy. You can create custom scripts in /usr/local/etc/rc.d/, make them executable, and enable them in /etc/rc.conf.

Key rc(8) Script Directives

Below are two example scripts.


Example 1: Create Directories on tmpfs

Create /usr/local/etc/rc.d/create_tmp_dirs with the following content:

#!/bin/sh
#
# PROVIDE: create_tmp_dirs
# REQUIRE: FILESYSTEMS
# BEFORE: DAEMON
 
. /etc/rc.subr
 
name="create_tmp_dirs"
rcvar=`set_rcvar`
 
start_cmd="create_dirs"
create_dirs() {
    mkdir -p /mnt/tmpfs/dir1
    mkdir -p /mnt/tmpfs/dir2
    # Add more directories as needed
}
 
load_rc_config $name
 
run_rc_command "$1"

Example 2: Run ntpdate Before ntpd

Create /usr/local/etc/rc.d/ntpdate_enable with the following content:

#!/bin/sh
#
# PROVIDE: ntpdate
# REQUIRE: NETWORKING
# BEFORE: NTPD
 
. /etc/rc.subr
 
name="ntpdate"
rcvar=`set_rcvar`
 
start_cmd="sync_time"
 
sync_time() {
    /usr/sbin/ntpdate -u 0.pool.ntp.org  # Change to your preferred NTP server
}
 
load_rc_config $name
 
run_rc_command "$1"

Final Steps

  1. Make the scripts executable:
        chmod +x /usr/local/etc/rc.d/create_tmp_dirs
        chmod +x /usr/local/etc/rc.d/ntpdate_enable
 
  1. Enable the scripts in /etc/rc.conf:
        create_tmp_dirs_enable="YES"
        ntpdate_enable="YES"
 

Now, when you reboot, create_tmp_dirs will run after filesystems are mounted but before daemons start, and ntpdate will run after networking is up but before ntpd starts.