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/bashExample:
#!/bin/bash1>&2 echo "Hello World"The file extension is .sh or .bash.
snake_case convention.Example 1:
integer=5export OS_LEVEL=5TITLE_SHARABLE_VARIABLE="the shared data for other script to source from"process_data() { ...}# rununset integerprocess_dataExample 2:
# Single functionmy_func() { ...}# Part of a packagemypackage::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_nameexport comes before the variable.local keyword. Use the naming convention for maximum POSIX compatibility.alias. Use function instead.Example:
# variable requires operationsGLOBAL_VARIABLE="$(ls)"export GLOBAL_VARIABLE# variable with only valueexport GLOBAL_LANGUAGE="en-US"# DO NOT do this. $(...) is an operationexport 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:
# BASHif [[ 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 ]]) ]]; thenelse ...fi# POSIX Compliantif [ -z "$filename" ]; then ...elif [ -z "$filename" ] && { [ -e "$filename" ] || [ -r "$filename" ] }; then ...else ...fi# BASHwhile [[ ([[ 5 != 0 || 5 != 4 ]]) && ([[ 5 != 0 || 5 != 4 ]]) ]]; do ...donefor item in "${list[@]}"; do ...done# POSIX Compliantwhile { [ 5 != 0 ] || [ 5 != 4 ] } && { [ 5 != 0 ] || [ 5 != 4 ] }; do ...donefor file in ./directory/*; do ...doneExample:
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 timetime is a shell keyword$That's all for BASH and SHELL script.