2015-09-08 14:08:14 +00:00
Coding style used for my bash projects (v2 Sep 2015)
2015-09-09 07:38:05 +00:00
++++ Header
Always use the following header
----BEGIN HEADER
#!/usr/bin/env bash
PROGRAM="program-name" # Long description
AUTHOR="(L) 20XX-20YY by Orsiris \"Ozy\" de Jong"
CONTACT="http://www.example.com me@example.com"
PROGRAM_BUILD=YYYYMMDDVV
## Optional instructions
----END HEADER
Using bind style versionning:
YYYYMMDDVV (Year, Month, Day, Revision): Example: 2015012402 = 2nd revision of 24 Jan 2015
++++ Indentation
2015-09-08 14:08:14 +00:00
Using tabs
Transform old shell scripts using unexpand command
2015-09-09 07:38:05 +00:00
++++ Comments
2015-09-08 14:08:14 +00:00
# Some comment
## Some important comment for the next function
################################################# Some separation
2015-09-09 07:38:05 +00:00
++++ Todo comments
Whenever there is some idea to postpone, use #TODO: (exact match for searches)
++++ Variables
All local variables are lowercase, separated by _ (ex: low_wait)
All global variables full upercase, separated by _ (ex: EXEC_TIME)
All instance variables (verbose, silent, etc) have prefix _ and are full upercase, separated by _ (ex: _VERBOSE)
++++ Functions
2015-09-08 14:08:14 +00:00
Every word in a function begins with an uppercase (ex: SomeFunctionDoesThings)
Define functions this way. Use sed ':a;N;$!ba;s/\n{\n/ {\n/g' to adapt when opening bracket is on a new line.
function something {
}
If function has some arguments, use local variable names that are more readable than $1...$n. Explain via comments what those variables contain if needed.
function anotherthing {
local var_name="${1}"
local other_var_name="${2}" # This variable contains stuff
}
Functions should always have return status
function thirdthing {
some_command
return $?
}
2015-09-09 07:38:05 +00:00
++++ Sub functions
2015-09-08 14:08:14 +00:00
When a function is a subroutine of another function, it is called _SomethingAsSubFunction
2015-09-09 07:38:05 +00:00
++++ If statements
2015-09-08 14:08:14 +00:00
If statements will be fully written (word "if" must be used). then is written on the same line.
(Use sed ':a;N;$!ba;s/]\n\t*then/]; then/g' to convert files to this format... Replace "],new line, zero or more tabs, then" by "; then")
if [ something ]; then
stuff
else
other stuff
fi
2015-09-09 07:38:05 +00:00
++++ Logging
2015-09-08 14:08:14 +00:00
A logging function is available with the following levels of logging:
- DEBUG: Only log this when DEBUG flas is set in program. Any command forged for eval should be logged by this.
- NOTICE: Standard messages
- WARN: Requires attention
- ERROR: Program produced an error but continues execution
- CRITICAL: Program execution is halted
2015-09-09 07:38:05 +00:00
++++ Eval
2015-09-08 14:08:14 +00:00
The eval command should always contain 2>1&.
There's a special case where this is needed:
eval "some;commands" 2>> "$LOG_FILE" in order to get error messages into the log.