Note
Some formatting rules are deprecated. New code should instead use shfmt
and call make sh-lint
.
Following this document is obligatory for all new code.
The rules are mostly sorted in the alphabetical order.
-
§ Avoid bashisms and GNUisms, prefer POSIX features only.
-
[!WARNING]
This rule is deprecated. See message at the beginning of the document.
Avoid spaces between patterns of the samecase
condition. -
§ Don't use the option
-q
of the commandls
. Some systems that use the Busybox version ofash
don't support it. -
§
export
andreadonly
should be used separately from variable assignment, because otherwise failures in command substitutions won't stop the script. That is, do this:X="$(echo 42)" export X
and not this:
# Bad! export X="$(echo 42)"
-
§ If a boolean value is needed, use
0
forfalse
, and1
fortrue
. -
§ Mark every variable that shouldn't change later as
readonly
. -
§ Prefer
'raw strings'
to"double quoted strings"
whenever possible. -
[!WARNING]
This rule is deprecated. See message at the beginning of the document.
Put spaces within$( cmd )
,$(( expr ))
, and{ cmd; }
. Avoid spaces within${var}
. -
§ Put utility flags in the ASCII order and don't group them together. For example,
ls -1 -A -l
. -
§ Script code lines should not be longer than one hundred (100) columns. For comments, see the text guidelines.
-
§
snake_case
, notcamelCase
for variables.kebab-case
for filenames. -
§ Start scripts with the following sections in the following order:
- Shebang.
- Some initial documentation (optional).
- Verbosity level parsing (optional).
set
options.
-
§ UPPERCASE names for external exported variables, lowercase for local, unexported ones.
-
§ Use
set -e -f -u
and alsoset -x
in verbose mode. -
§ Use the
"$var"
form instead of the$var
form, unless word splitting is required. -
§ When concatenating, always use the form with curly braces to prevent accidental bad variable names. That is,
"${var}_tmp.text"
and not"$var_tmp.text"
. The latter will try to lookup variablevar_tmp
. -
§ When concatenating, surround the whole string with quotes. That is, use this:
dir="${TOP_DIR}/sub"
and not this:
# Bad! dir="${TOP_DIR}"/sub
Guidelines and agreements for using command test
, also known as [
:
-
§ For conditionals that check for equality against multiple values, prefer
case
instead oftest
. -
§ Prefer the
!= ''
form instead of using-n
to check if string is empty. -
§ Spell compound conditions with
&&
,||
, and!
outside oftest
instead of-a
,-o
, and!
inside oftest
correspondingly. The latter ones are pretty much deprecated in POSIX.See also: “Problems With the
test
Builtin: What Does-a
Mean?”. -
§ Use
=
for strings and-eq
for numbers to catch typing errors.