Skip to content
Matt Churchyard edited this page Apr 11, 2016 · 11 revisions

Variables

In general we take the following format for variables:

Global - ${ALL_CAPS}
Local  - ${_variable}

Unless variables are designed to be global, they should always be declared at the top of the current function using local. Quite often functions are designed to modify variables declared in a parent function. In this case, the variable should be listed in the @modifies list in the function description to make it clear that the function modifies variables declared outside of its scope.

All variables are accessed using braces - ${_variable}

Functions

All functions start with two underscores

__function_name

Where it makes sense, function names also make it clear where they are defined

__vm_zfs_* - ./lib/vm-zfs
__vm_switch_* - ./lib/vm-switch
__config_* - ./lib/vm-config

We preceed all functions with a small description that explains what the function does, and lists arguments and/or return values.

Coding Style

Commenting

Any code should be well commented, especially if it's not instantly clear exactly what the code is doing.

Indentation

All code should be correctly indented, using 4 spaces.

If Statements

If statements are written as follows. If there are multiple statements, there should be a blank line inbetween.

# check something
if [ test ]; then
    code
fi

# check something else
if [ test2 ]; then
    code2
fi

Where appropriate, tests are reduced to one line for brevity and clarity

[ "check 1" ] && __err "Some error"
[ "check 2" ] && __err "Another error"
Return Values

Where it makes sense, functions return 0 on success, or any other integer on error. For return values we prefer using setvar, rather than $(func) and echo, which requires a subshell. Not using a subshell has been shown to improve performance.

__good_function(){
    local _var="$1"

    setvar "${_var}" "return value"
}

__bad_function(){

    echo "return value"
}

_variable=$(__bad_function)
__good_function "_variable"
Case Statements

In general, ;; should be placed on a new line to improve readability. The exception to this is when each case only contains one line, where adding ;; on a newline would needlessly increase code length. The function calls should however be lined up.

case "${_variable}" in
    one)   __func_one ;;
    two)   __func_two ;;
    three) __func_three ;;
esac