Skip to content

Instantly share code, notes, and snippets.

@forestbaker
Last active November 24, 2015 17:19
Show Gist options
  • Save forestbaker/d89731b9a27d63617432 to your computer and use it in GitHub Desktop.
Save forestbaker/d89731b9a27d63617432 to your computer and use it in GitHub Desktop.
shell style guide & design philosophy
Complex Shell Script Outline
----------------------------
header
begin script
preamble:
- sanity checks
- create shell environ
- log & debug
error handling
check dependencies
load libraries
declare environment constants
declare environment variables
declare main function
execute main function
verify success
return result
footer
end script
clean up
--------------------------
cartouche:
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# [ forest baker | script name | company name
# +-----------------------------------------------+
# [ release date | unique id | version
# +-----------------------------------------------+
# [ description
# +-----------------------------------------------+
# [ license: | caveat emptor | ars gratia artis
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#====| section }==========================================================>
# set up log and debug
#=========================================================================>
#----| comment )----------------------------------------------------------+
# this is an important comment
#-------------------------------------------------------------------------+
#====| function ]============#=============#==============#================#
# name :
# purpose :
# example :
#==========================================================================#
variable name style:
- at least 3 characters
- must start with _ or Aa-Zz
global variables or constants:
'ALL_CAPS' 'MY_VARIABLE'
local variables or constants:
'lower_case' 'my_variable'
alias style:
'Camel_Case' 'Camel'
functions:
'camelCase' 'CamelCase' 'lowercase'
#prefix library name of sourced functions - or not
#mainlib.functionName
# Design Philosophy
Open Source -
1. comment logographic hieroglyphics!
2. fail loudly and quickly!
3. a robust program is the product of transparency & simplicity
- simplicity: KISS! abhor lexicon complexity! KISS!
- transparency: visibile source, invite peer inspection, make debugging easy!
4. redux, reuse, recycle, repeat
5. interface design: do the least surprising thing, do the most expected thing
6. write simple programs connected by clean interfaces
7. clearly communicate what is happening (when necessary)
- print information about what the program is doing and if it was successful
- handle errors with grace (or fail and make a lot of noise)
- explain the situation and provide potential solutions to the user
8. produce log files and reports with human readable information pertinent to the program (what is happening?)
9. know the present working directory (where am i?)
10. know thyself (who am i?)
11. check it before you wreck it
- make sure a file exists before modifying it
- verify the modification was successful
12. be careful / avoid automating destructive commands
- rename and copy original files to a separate directory
- remove the directory contents if the program ends successfully
UNIX -
1. Least privilege: Grant sufficient access to accomplish the task. "What privilege does the software require?" not, "What privilege does the software want?"
2. Economy of mechanism: Short and simple code has fewer bugs than long and complex.
3. Determine the minimum necessary to do the job.
4. Complete mediation: Check every access to an object, every return code from every call, and every variable value at a decision.
5. Open design: Security through obscurity is unreliable. With more eyes able to read, more bugs get squashed.
6. Separation of privilege: Use different routines or programs for privileges necessary at different times.
7. Least common mechanism: Avoid granting access to shared resources / minimize shared resources.
8. Psychological acceptability: Security controls must be easy to use or they will be bypassed by users.
9. Fail-safe defaults: Deny by default, and fail without granting the request.
10. Reuse code: Reuse previously tested code.
11. Distrust the unknown: Anything provided by users or from outside of the program is suspect.
12. Anticipate problems: During design phase, mitigate or minimize security risks, think ahead.
# Predictability
Layout script in sections using 'A Shell Script Outline'
- never use inline comments # may get the entire line removed. consider grep -v '#'
- date & time: YYYYMMDD_hhmmss GMT timezone
- pathnames do not end in a trailing slash
- declare all variables
- use absolute paths
- Do NOT add the working directory to $PATH (remove .)
https://www.chromium.org/chromium-os/shell-style-guidelines
- prefer printf over echo
- Arithmetic
: $(( i += 1 ))
: $(( i -= 1 ))
- Default Variable Assignment
: assign bar to foo if foo is not set or set to "": ${foo:=bar}
: assign bar to foo only if it is not set: ${foo=bar}
- Use getopts & shflags when accepting options from command line
http://lug.fh-swf.de/vim/vim-bash/StyleGuideShell.en.pdf
- total line length must not exceed 88 characters
- use self-documenting variable names
- use here documents for multi-line text
- verify program successfully executed
- display a summary report for interactive scripts
- write execution actions to logfile
- use --long-forms of command line options
- mitigate SUID/SGID script risk
http://www.inquisitor.ru/doc/coding-style-shell.html
- use lines of 72 characters long
- comments go above the line they refer to
- delimit pipe character with spaces before & after: ' | '
- <, >, 2> delimit redirection operators with space before, not after
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment