Managing FreeBSD system services

From ZS64
Jump to navigationJump to search

FreeBSD uses scripts in /etc/rc.d (and other directories) to manage system services: start or stop them, obtain status or configuration information, and so on.

Running these scripts from the command line by typing in the full path is tedious and error prone. Also, because there's at least three directories where these scripts reside, you have to remember which path to use when invoking them.

This bash auto-completion command allows tabbing through all possible choices:

# Run FreeBSD rc scripts; auto-completes script name and command

_rc() {
    local _cur _prev _opts _i0 _i1 _i2 _s0 _s1
    COMPREPLY=()
    _cur="${COMP_WORDS[COMP_CWORD]}"
    _prev="${COMP_WORDS[COMP_CWORD-1]}"
    case ${COMP_CWORD} in
        1)
            _opts="$(/bin/ls /etc/rc.d; /bin/ls /usr/local/etc/rc.d; /bin/ls /usr/X11R6/bin)"
            COMPREPLY=( $(compgen -W "${_opts}" -- ${_cur}) )
            return 0
            ;;
        2)
            for _i0 in /etc/rc.d /usr/local/etc/rc.d /usr/X11R6/bin; do
                if [ -x ${_i0}/${_prev} ]; then
                    _s0=$(${_i0}/${_prev} 2>&1 | sed -e 's#.*(\(.*\)).*$#\1#' -e 's#|# #g')
                    _s1=$(${_i0}/${_prev} 2>&1 | sed -e 's#.*\[\([^]]*\)\].*#\1#' -e 's#|# #g')
                    _opts=""
                    for _i1 in ${_s0}; do
                        for _i2 in "" ${_s1}; do
                            _opts="${_opts} ${_i2}${_i1}"
                        done
                    done
                    COMPREPLY=( $(compgen -W "${_opts}" -- ${_cur}) )
                    return 0
                fi
            done
            ;;
    esac
}

rc() {
    local cmd
    cmd="$1"
    shift
    if [ -z "$cmd" ]; then
        echo "Usage: rc rcscript command" >&2
        return 64
    fi
    for i in /etc/rc.d /usr/local/etc/rc.d /usr/X11R6/bin; do
        if [ -x ${i}/${cmd} ]; then
            ${i}/${cmd} $@
            return $?
        fi
    done
    echo "Unknown rc command \"${cmd}\"." >&2
}

complete -F _rc rc