On this page
Shell coding guidelines
Overview
Shell scripts (such as initscripts) and shell commands inside other files should follow these conventions.
General rules
- Shebang should always be added.
- Variables should always be double-quoted (except when that would change the intent).
- Suggested practices for target shell should be used - if writing for bash, $() instead of backticks, etc.
- If writing for sh, a minimum subset of other utility functionality
should be used (for example,
sed -ishould not be used as it might not be supported on some Unices). - In variable comparisons, consider using
xyessyntax. See Stackoverflow question on that. - If you have to write to a file that other process might read and that might result in a race condition (where writing to the file has not been completed yet), use mv, as it must be atomic according to POSIX.
- If you have to create locking in a shell script, use directories, not files. mkdir is atomic, thus mkdir lockdir should never allow two processes to lock at the same time.
- Don't use cat where it is not needed. Use grep string file instead of cat file | grep string. Also see Useless use of cat.
- Read BashFAQ.
Formatting
- Pipe character should have single space on each side if used for command chaining:
ifconfig eth0 | grep "inet addr"
- Stream redirection characters should have single space on each side, too:
create/schema/gen.pl c > src/libs/zbxdbhigh/dbschema.c
- When defining an array, add spaces inside the parenthesis:
array=( a b )
* Except when defining an empty array:
array=()