unix:freebsd:bootscripts

Boot Time Scripts on FreeBSD

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

  • Synchronizing the system clock: If your system clock drifts too far out of sync, ntpd may not be able to correct it. Running ntpdate before ntpd starts can solve this.
  • Creating directories on tmpfs: If you mount /var/log or other directories on a ramdisk (tmpfs), some applications may fail if their required directories do not exist. You need to create these directories after filesystems are mounted but before daemons start.

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

  • PROVIDE: The service this script provides. Used to determine execution order.
  • REQUIRE: Services that must start before this script runs.
  • BEFORE: Services that must start after this script runs.

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.

unix/freebsd/bootscripts.txt · Last modified: by rodolico