RC.SUBR(8)
πΈ NAME πΈ
okay bestie, this is RC.SUBR(8) from the System Manager's Manual β the page for rc.subr, aka functions used by system shell scripts. Welcome to the group chat π
β¨ SYNOPSIS β¨
. /etc/rc.subr
backup_file action file current backup
checkyesno var
check_pidfile pidfile procname [interpreter]
check_process procname [interpreter]
DebugOn tag ...
DebugOff tag ...
debug message
dot file ...
err exitval message
force_depend name
info message
is_verified file
load_kld [-e regex] [-m module] file
load_rc_config [flag] [service]
load_rc_config_var name var
mount_critical_filesystems type
rc_log message
rc_trace level message
rc_usage command ...
reverse_list item ...
run_rc_command argument
run_rc_script file argument
run_rc_scripts [options] file ...
safe_dot file ...
sdot file ...
startmsg [-n] message
vdot file ...
wait_for_pids [pid ...]
warn message
π¦ DESCRIPTION π¦
okay so the rc.subr script is basically the communal backpack of commonly used shell script functions and variable definitions that various scripts such as rc(8) use. Scripts required by ports in /usr/local/etc/rc.d will also eventually be rewritten to make use of it. <stars>β¨</stars>
The rc.subr functions were mostly imported from NetBSD. They are accessed by sourcing /etc/rc.subr into the current shell. The following shell functions are available:
πΎ backup_file action file current backup
Make a backup copy of file into current. Save the previous version of current as backup.
The action argument may be one of the following:
addβfileis now being backed up by or possibly re-entered into this backup mechanism.currentis created.updateβfilehas changed and needs to be backed up. Ifcurrentexists, it is copied tobackupand thenfileis copied tocurrent.removeβfileis no longer being tracked by this backup mechanism.currentis moved tobackup.
β
checkyesno var
Return 0 if var is defined to YES, TRUE, ON, or 1. Return 1 if var is defined to NO, FALSE, OFF, or 0. Otherwise, warn that var is not set correctly. The values are case insensitive.
Note:varshould be a variable name, not its value;checkyesnowill expand the variable by itself. π«Ά
π check_pidfile pidfile procname [interpreter]
Parses the first word of the first line of pidfile for a PID, and ensures that the process with that PID is running and its first argument matches procname. Prints the matching PID if successful, otherwise nothing.
If interpreter is provided, parse the first line of procname, ensure that the line is of the form:
#! interpreter [...]
and use interpreter with its optional arguments and procname appended as the process string to search for.
π΅οΈ check_process procname [interpreter]
Prints the PIDs of any processes that are running with a first argument that matches procname. interpreter is handled as per check_pidfile.
π DebugOn tag ...
Enable tracing if not already enabled, and any tag is found in DEBUG_SH (a comma separated list of tags).
Record the tag that caused it to be enabled in DEBUG_ON, set DEBUG_DO empty and DEBUG_SKIP to :.
See debug.sh(8) for more details.
π DebugOff tag ...
Disable tracing if enabled and any tag matches DEBUG_ON, which means it was the reason tracing was enabled.
Set DEBUG_DO to :, and DEBUG_ON, DEBUG_SKIP empty.
π debug message
Display a debugging message to stderr, log it to the system log using logger(1), and return to the caller. The error message consists of the script name (from $0), followed by : DEBUG: , and then message.
This function is intended to be used by developers as an aid to debugging scripts. It can be turned on or off by the rc.conf(5) variable rc_debug.
π dot file ...
For reading in unverified files.
Ensure shell verify option is off. This option is only meaningful when mac_veriexec(4) is active.
Read each file if it exists.
Restore previous state of the verify option.
π₯ err exitval message
Display an error message to stderr, log it to the system log using logger(1), and exit with an exit value of exitval. The error message consists of the script name (from $0), followed by : ERROR: , and then message.
π«΅ force_depend name
Output an advisory message and force the name service to start. The name argument is the basename(1) component of the path to the script located at /etc/rc.d (scripts stored in other locations such as /usr/local/etc/rc.d cannot be controlled with force_depend currently).
If the script fails for any reason it will output a warning and return with a return value of 1. If it was successful it will return 0.
π§Ύ is_verified file
If veriexec(8) does not exist, or mac_veriexec(4) is not active, just return success. Otherwise use veriexec(8) to check if file is verified. If not verified the return code will be 80 (EAUTH).
π¬ info message
Display an informational message to stdout, and log it to the system log using logger(1). The message consists of the script name (from $0), followed by : INFO: , and then message.
The display of this informational output can be turned on or off by the rc.conf(5) variable rc_info.
π§© load_kld [-e regex] [-m module] file
Load file as a kernel module unless it is already loaded. For the purpose of checking the module status, either the exact module name can be specified using -m, or an egrep(1) regular expression matching the module name can be supplied via -e. By default, the module is assumed to have the same name as file, which is not always the case.
βοΈ load_rc_config [flag] [service]
Source in the configuration file(s) for service. If no service is specified, only the global configuration file(s) will be loaded. First, /etc/rc.conf is sourced if it has not yet been read in. Then, /etc/rc.conf.d/service is sourced if it is an existing file. The latter may also contain other variable assignments to override run_rc_command arguments defined by the calling script, to provide an easy mechanism for an administrator to override the behaviour of a given rc.d(8) script without requiring the editing of that script.
The function named by load_rc_config_reader (default is dot) is used to read configuration unless flag is:
-sβ usesdotto read configuration, because we want verified configuration or to usesafe_dotto read an unverified configuration.-vβ usevdotto read in configuration only if it is verified.
DebugOn will be called with tags derived from name to enable tracing if any appear in DEBUG_SH.
π load_rc_config_var name var
Read the rc.conf(5) variable var for name and set in the current shell, using load_rc_config in a sub-shell to prevent unwanted side effects from other variable assignments.
π» mount_critical_filesystems type
Go through a list of critical file systems, as found in the rc.conf(5) variable critical_filesystems_type, mounting each one that is not currently mounted.
πͺ΅ rc_log message
Output message with a timestamp, which is both human readable and easily parsed for post processing, using:
date "+@ %s [%Y-%m-%d %H:%M:%S %Z] $*"
π§΅ rc_trace level message
If the file /etc/rc.conf.d/rc_trace exists and is not empty attempt to set RC_LEVEL based on its content. If the file is empty or does not contain a value for RC_LEVEL, set it to 0.
If level is greater than or equal to RC_LEVEL pass message to rc_log.
π£ rc_usage command ...
Print a usage message for $0, with commands being the list of valid arguments prefixed by [fast|force|one|quiet].
π reverse_list item ...
Print the list of items in reverse order.
π run_rc_command argument
Run the argument method for the current rc.d(8) script, based on the settings of various shell variables. run_rc_command is extremely flexible, and allows fully functional rc.d(8) scripts to be implemented in a small amount of shell code.
argument is searched for in the list of supported commands, which may be one of:
startβ Start the service. This should check that the service is to be started as specified byrc.conf(5). Also checks if the service is already running and refuses to start if it is. This latter check is not performed by standard FreeBSD scripts if the system is starting directly to multi-user mode, to speed up the boot process.stopβ If the service is to be started as specified byrc.conf(5), stop the service. This should check that the service is running and complain if it is not.restartβ Perform a stop then a start. Defaults to displaying the process ID of the program (if running).enabledβ Return0if the service is enabled and1if it is not. This command does not print anything.rcvarβ Display whichrc.conf(5)variables are used to control the startup of the service (if any).
If pidfile or procname is set, also support:
pollβ Wait for the command to exit.statusβ Show the status of the process.
Other supported commands are listed in the optional variable extra_commands.
argument may have one of the following prefixes which alters its operation:
fastβ Skip the check for an existing running process, and setsrc_fast=YES.forceβ Skip the checks forrcvarbeing set to"YES", and setsrc_force=YES. This ignoresargument_precmdreturning non-zero, and ignores any of therequired_*tests failing, and always returns a zero exit status.oneβ Skip the checks forrcvarbeing set to"YES", but performs all the other prerequisite tests.quietβ shhh era π€« this prefix inhibits some of the verbose diagnostics. Right now that means the messages"Starting ${name}"(as checked bycheck_startmsgsinsiderc.subr) and the errors you'd get about usage of services that aren't enabled in rc.conf(5). This prefix also setsrc_quiet=YES.
bestie pls note: rc_quiet is not meant to completely mask all debug and warning messages β only certain small classes of them. it's giving "mute the group chat, not your alarm" π
π the shell variables run_rc_command uses to control its behaviour
Unless otherwise stated, all of these are optional β¨
nameβ the name of this script. This one is not optional, she is mandatory, main character energy πrcvarβ the value ofrcvargets checked withcheckyesnoto figure out if this method should even be run.commandβ full path to the command. Not required ifargument_cmdis defined for each supported keyword. Can be overridden by${name}_program.command_argsβ optional arguments and/or shell directives forcommand.command_interpreterβcommandis started with:
#! command_interpreter [...]
which results in its ps(1) command being:
command_interpreter [...] command
so use that string to find the PID(s) of the running command rather than command. iykyk π«Ά
extra_commandsβ extra commands/keywords/arguments supported. yes she does extra πpidfileβ path to PID file. Used to determine the PID(s) of the running command. Ifpidfileis set, use:
check_pidfile $pidfile $procname
to find the PID. Otherwise, if command is set, use:
check_process $procname
to find the PID.
procnameβ process name to check for. Defaults to the value ofcommand.required_dirsβ check for the existence of the listed directories before running thestartmethod. The list is checked before runningstart_precmd.required_filesβ check for the readability of the listed files before running thestartmethod. The list is checked before runningstart_precmd.required_modulesβ ensure the listed kernel modules are loaded before running thestartmethod. The list is checked after runningstart_precmd. why? because it's done after invoking the commands fromstart_precmdso that missing modules aren't loaded in vain if those preliminary commands indicate an error condition β no loading things for no reason, we're efficient πΈ A word in the list can have an optionalβ:modnameβorβ~patternβsuffix. The modname or pattern parameter is passed toload_kldthrough a-mor-eoption, respectively. See the description ofload_kldin this document for details.required_varsβ performcheckyesnoon each of the list variables before running thestartmethod. The list is checked after runningstart_precmd.${name}_chdirβ directory tocdto before runningcommand, if${name}_chrootis not provided.${name}_chrootβ directory to chroot(8) to before runningcommand. Only supported after/usris mounted.${name}_envβ a list of environment variables to runcommandwith. Those variables will be passed as arguments to the env(1) utility unlessargument_cmdis defined. In that case the contents of${name}_envwill be exported via theexport(1)builtin of sh(1), which puts some limitations on the names of variables (e.g., a variable name may not start with a digit π).${name}_env_fileβ a file to source for environmental variables to runcommandwith.
Note: all the variables which are being assigned in this file are going to be exported into the environment of command. all of them. no takebacks π
${name}_fibβ FIB Routing Table number to runcommandwith. See setfib(1) for more details.${name}_flagsβ arguments to callcommandwith. This is usually set in rc.conf(5), and not in the rc.d(8) script. The environment variable'flags'can be used to override this.${name}_niceβ nice(1) level to runcommandas. Only supported after/usris mounted.${name}_limitsβ resource limits to apply tocommand. This will be passed as arguments to the limits(1) utility. By default, the resource limits are based on the login class defined in${name}_login_class.${name}_login_classβ login class to use with${name}_limits. Defaults toβdaemonβ.${name}_offcmdβ shell commands to run duringstartif a service is not enabled. like, off-duty behaviour π¦${name}_oomprotectβ protect(1)commandfrom being killed when swap space is exhausted. IfβYESβis used, no child processes are protected. IfβALLβ, protect all child processes.${name}_programβ full path to the command. Overridescommandif both are set, but has no effect ifcommandis unset. As a rule,commandshould be set in the script while${name}_programshould be set in rc.conf(5).${name}_userβ user to runcommandas, using chroot(8) if${name}_chrootis set, otherwise uses su(1). Only supported after/usris mounted.${name}_groupβ group to run the chrooted command as.${name}_groupsβ comma separated list of supplementary groups to run the chrooted command with.${name}_prependβ commands to be prepended tocommand. This is a generic version of${name}_env,${name}_fib, or${name}_nice.${name}_setupβ optional command to be run duringstart,restart, andreloadprior to the respectiveargument_precmd. If the command fails for any reason it will output a warning, but execution will continue. resilient queen πargument_cmdβ shell commands which override the default method for argument.argument_precmdβ shell commands to run just before runningargument_cmdor the default method for argument. If this returns a non-zero exit code, the main method is not performed. If the default method is being executed, this check is performed after therequired_*checks and process (non-)existence checks.argument_postcmdβ shell commands to run if runningargument_cmdor the default method for argument returned a zero exit code.sig_stopβ signal to send the processes to stop in the defaultstopmethod. Defaults toSIGTERM.sig_reloadβ signal to send the processes to reload in the defaultreloadmethod. Defaults toSIGHUP.
π the default methods (what happens when argument_cmd isn't defined)
For a given method argument, if argument_cmd is not defined, then a default method is provided by run_rc_command:
startβ ifcommandis not running andcheckyesno rcvarsucceeds, startcommand. go bestie go π₯stopβ determine the PIDs ofcommandwithcheck_pidfileorcheck_process(as appropriate), kill those PIDs withsig_stop, and runwait_for_pidson those PIDs.reloadβ similar tostop, except that it usessig_reloadinstead, and does not runwait_for_pids. Another difference fromstopis thatreloadis not provided by default. It can be enabled viaextra_commandsif appropriate:
extra_commands=reload
restartβ runs thestopmethod, then thestartmethod. the full cycle, the character arc πstatusβ show the PID ofcommand, or some other script specific status operation.pollβ wait forcommandto exit.rcvarβ display which rc.conf(5) variable is used (if any). This method always works, even if the appropriate rc.conf(5) variable is set toβNOβ. iconic, honestly π
The following variables are available to the methods (such as argument_cmd) as well as after run_rc_command has completed:
rc_argβ the argument that got handed torun_rc_command, after thefastandforceprocessing has already happened. so like, post-glow-up version of the arg πrc_flagsβ the flags you start the default command with. it defaults to${name}_flags, unless the environment variableflagsoverrides it. and yeah, theargument_precmdmethod is allowed to change this variable. main character behaviour honestly.rc_serviceβ the path to the service script being executed, just in case it ever needs to re-invoke itself. self-care, but make it shell π«Άrc_pidβ the PID of the command (if appropriate).rc_fastβ not empty if thefastprefix was used.rc_forceβ not empty if theforceprefix was used.
β¨ run_rc_script file argument
okay so this one starts the script file with an argument of argument, and then handles whatever return value the script throws back at it. no cap, it's the handler π
bunch of shell variables get unset before file is started, so it's a clean slate:
name, command, command_args, command_interpreter,
extra_commands, pidfile, rcvar, required_dirs,
required_files, required_vars, argument_cmd,
argument_precmd. argument_postcmd.
then it calls rc_trace to announce that file is about to be run. spooky foreshadowing, love that for us.
but β if is_verified file fails, it just returns. nothing else happens. bye bestie π
DebugOn gets called with tags derived from name and rc_arg, so tracing can turn on if any of those tags show up in DEBUG_SH. iykyk.
run_rc_script executes file unless:
fileends in.shand lives in/etc/rc.d.filelooks like a backup or scratch file (e.g., with a suffix of~,#,.OLD,,v, or.orig).fileis not executable.
β¨ run_rc_scripts [options] file ...
calls run_rc_script for each file, unless that file is already recorded as having been run. we do not do repeats in this house π
ββοΈ
the options are:
--arg argβ passargtorun_rc_script. the default is_boot, set by rc(8).--break breakβ stop processing if any file matches anybreak
β¨ safe_dot file ...
this one's used by sdot when mac_veriexec(4) is active and file is not verified.
it limits the input from file to simple variable assignments, with any non-alphanumeric characters swapped out for _. literally keeping it safe, keeping it simple π
β¨ sdot file ...
for reading in configuration files! it skips files that don't exist or are empty. then it tries vdot, and if that fails (because the file is unverified) it falls back to safe_dot. bestie has a backup plan π
β¨ startmsg [-n] message
displays a start message to stdout. and like, it should be used instead of echo(1) β that's the vibe. the display of this output can be turned off if the rc.conf(5) variable rc_startmsgs is set to "NO". rude but okay π
β¨ stop_boot [always]
prevents booting to multiuser mode. if the autoboot variable is set to yes (see rc(8) to learn more about autoboot), or checkyesno always indicates a truth value, then a SIGTERM signal gets sent to the parent process, which is assumed to be rc(8). otherwise, the shell exits with a non-zero status. dramatic exit, honestly iconic π
β¨ vdot file ...
for reading in only verified files. very exclusive, very VIP π
it ensures the shell verify option is on. this option is only meaningful when mac_veriexec(4) is active β otherwise this function is effectively the same as dot. (yes, with the little dot. no drama.)
it reads in each file if it exists and is_verfied file is successful, otherwise it sets the return code to 80 (EAUTH). then it restores the previous state of the verify option. polite and thorough π«Ά
β¨ wait_for_pids [pid ...]
waits until all the pids you handed it don't exist any more, printing the list of outstanding pids every two seconds. clock is ticking bestie β
β¨ warn message
displays a warning message to stderr and logs it to the system log using logger(1). the warning message is made of the script name (from $0), followed by ": WARNING: ", and then message. so like scriptname: WARNING: your thing, periodt π₯
π FILES
/etc/rc.subrβ therc.subrfile resides in/etc. that's it, that's the file π
πΈ SEE ALSO
rc.conf(5), debug.sh(8), rc(8)
π HISTORY
The rc.subr script appeared in NetBSD 1.3. the rc.d(8) support functions appeared in NetBSD 1.5. and the rc.subr script first appeared in FreeBSD 5.0. a whole glow-up timeline, we love a documented origin story β¨
k that's the whole page, bestie, you're officially an rc.subr scholar ππ this one's from the Debian edition, dated October 23, 2024, and yes it's RC.SUBR(8) β section 8, system admin territory, very serious, very slay π¦
π¦ where this page comes from
- freebsd 15.1: base 15.1
- Copyright (c) 2002-2004 The NetBSD Foundation, Inc
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms