These are the BASH and SHELL language-specific coding styles. Anything mentions here overrides/adds to the "In General" guides.
Always include Shebang Line in Line 1. Period.. You’ll break your script and let your user crying to figure out which Shell program to use if you avoid it. A Shebang line is:
#!/bin/bash
Example:
#!/bin/bash
1>&2 echo "Hello World"
The file extension is .sh
or .bash
.
snake_case
convention.Example 1:
integer=5
export OS_LEVEL=5
TITLE_SHARABLE_VARIABLE="the shared data for other script to source from"
process_data() {
...
}
# run
unset integer
process_data
Example 2:
# Single function
my_func() {
...
}
# Part of a package
mypackage::my_func() {
...
}
{
after the function naming since it breaks the script.export
comes after the function declaration.unset
your functions after used.Example:
function_name() {
echo "Hello World"
}
export -f function_name
export
comes before the variable.local
keyword. Use the naming convention for maximum POSIX compatibility.alias
. Use function
instead.Example:
# variable requires operations
GLOBAL_VARIABLE="$(ls)"
export GLOBAL_VARIABLE
# variable with only value
export GLOBAL_LANGUAGE="en-US"
# DO NOT do this. $(...) is an operation
export GLOBAL_VARIABLE="$(ls)"
It’s a terminal script.
[[ ... ]]
for bash while [ ... ]
for POSIX compliant.[
or [[
.]
or ]]
.then
or do
should shares the same line as if
, elif
, while
and for
respectively.;
); 1 space after; then then
or do
comes later.Example:
# BASH
if [[ 5 != 0 ]]; then
...
elif [[ 5 != 0 || 5 != 4 ]]; then
...
elif [[ ([[ 5 != 0 || 5 != 4 ]]) && ([[ 5 != 0 || 5 != 4 ]]) ]]; then
...
elif [[ ([[ 5 != 0 || 5 != 4 ]]) &&
([[ 5 != 0 || 5 != 4 ]]) &&
([[ 5 != 0 || 5 != 4 ]]) &&
([[ 5 != 0 || 5 != 4 ]]) ]]; then
else
...
fi
# POSIX Compliant
if [ -z "$filename" ]; then
...
elif [ -z "$filename" ] && { [ -e "$filename" ] || [ -r "$filename" ] }; then
...
else
...
fi
# BASH
while [[ ([[ 5 != 0 || 5 != 4 ]]) && ([[ 5 != 0 || 5 != 4 ]]) ]]; do
...
done
for item in "${list[@]}"; do
...
done
# POSIX Compliant
while { [ 5 != 0 ] || [ 5 != 4 ] } && { [ 5 != 0 ] || [ 5 != 4 ] }; do
...
done
for file in ./directory/*; do
...
done
Example:
Add() {
echo "$((1 + 2))"
return 0
}
1>&2 echo -n "This is a status message. Doing 5 + 3 = "
Add 5 3
$(...)
instead of backtick `...`
."$(...)"
) the output.Example:
# This is preferred:
var="$(command "$(command1)")"
# This is not:
var="`command \`command1\``"
Example:
$ type time
time is a shell keyword
$
That's all for BASH and SHELL script.