Now let us add some controls to our dummy script. As you may know, rc.d scripts are controlled with rc.conf(5). Fortunately, rc.subr(8) hides all the complications from us. The following script uses rc.conf(5) via rc.subr(8) to see whether it is enabled in the first place, and to fetch a message to show at boot time. These two tasks in fact are independent. On the one hand, an rc.d script can just support enabling and disabling its service. On the other hand, a mandatory rc.d script can have configuration variables. We will do both things in the same script though:
#!/bin/sh . /etc/rc.subr name=dummy rcvar=dummy_enable start_cmd="${name}_start" stop_cmd=":" load_rc_config $name : ${dummy_enable:=no} : ${dummy_msg="Nothing started."} dummy_start() { echo "$dummy_msg" } run_rc_command "$1"
What changed in this example?
load_rc_config
is invoked earlier in the
script, before any rc.conf(5) variables
are accessed.Note: While examining rc.d scripts, keep in mind that sh(1) defers the evaluation of expressions in a function until the latter is called. Therefore it is not an error to invoke
load_rc_config
as late as just beforerun_rc_command
and still access rc.conf(5) variables from the method functions exported torun_rc_command
. This is because the method functions are to be called byrun_rc_command
, which is invoked afterload_rc_config
.
run_rc_command
if
rcvar itself is set, but the indicated knob variable is
unset. If your rc.d script is for the base system,
you should add a default setting for the knob to /etc/defaults/rc.conf and document it in rc.conf(5). Otherwise
it is your script that should provide a default setting for the knob. The canonical
approach to the latter case is shown in the example.Note: You can make rc.subr(8) act as though the knob is set to ON, irrespective of its current setting, by prefixing the argument to the script with one or force, as in
onestart
orforcestop
. Keep in mind though that force has other dangerous effects we will touch upon below, while one just overrides the ON/OFF knob. E.g., assume that dummy_enable is OFF. The following command will run thestart
method in spite of the setting:# /etc/rc.d/dummy onestart
Important: The names of all rc.conf(5) variables used exclusively by our script must have the same prefix: ${name}_. For example: dummy_mode, dummy_state_file, and so on.
Note: While it is possible to use a shorter name internally, e.g., just msg, adding the unique prefix ${name}_ to all global names introduced by our script will save us from possible collisions with the rc.subr(8) namespace.
As a rule, rc.d scripts of the base system need not provide defaults for their rc.conf(5) variables because the defaults should be set in /etc/defaults/rc.conf instead. On the other hand, rc.d scripts for ports should provide the defaults as shown in the example.
start_cmd="echo \"$dummy_msg\""