My Coding Rules for Bash Scripts

This collection now includes examples of simple and complex functions, with and without parameters, providing a comprehensive reference for coding Bash scripts. Starting from the basic and going to the less-used solution.

1. Shebang

Start each script with a shebang line to indicate the interpreter to use:

#!/bin/bash

2. Permissions

Ensure that the script has execution permissions:

chmod +x script_name.sh

3. Comments

Use comments to explain the code:

# This is a comment

4. Variables

Variable Declaration

  • Declare variables without spaces around the equal sign:
name="value"
  • Default Values: Use the syntax ${variable:-default_value} to set a default value if the variable is not defined:
name=${name:-"default_value"}

Variable Processing

  • Uppercase:
uppercase=${name^^}
  • Lowercase:
lowercase=${name,,}
  • Capitalization (first letter uppercase):
capitalize=${name^}
  • Inline Character Replacement: Use the syntax ${variable//old/new} to replace all occurrences of a substring with another:
new_name=${name//old/new_value}

5. Input Parameters

Bash scripts can receive input parameters, which can be processed in various ways:

  • $1, $2, …: Represent the first parameters passed to the script. For example, $1 is the first argument, $2 is the second, etc.

  bash
  echo "First parameter: $1"
  

  • $#: Indicates the total number of parameters passed to the script.

  bash
  echo "Number of parameters: $#"
  

  • $@: Represents all parameters passed to the script as a list. Used in a loop to process each argument.

  bash
  for param in "$@"; do
      echo "Parameter: $param"
  done
  

  • $*: Similar to $@, but all parameters are treated as a single string.

  bash
  echo "All parameters: $*"
  

  • $?: Represents the return code of the last executed command.

  bash
  echo "Return code: $?"
  

6. Conditions

Use if, then, else for conditional structures:

if [ condition ]; then
    # commands
else
    # other commands
fi

7. switch case Structures

Use case to handle multiple conditions more readably. You can process multiple possible values by separating them with spaces:

case $variable in
    value1 | value2 | value3)
        # commands for value1, value2, or value3
        ;;
    value4)
        # commands for value4
        ;;
    *)
        # default commands
        ;;
esac

8. Functions

Function Examples

Simple Function (no parameters)

my_simple_function() {
    echo "This is a simple function."
}

# Call the function
my_simple_function

Function with Parameters

my_function_with_parameters() {
    param1=$1
    param2=$2
    echo "Parameter 1: $param1"
    echo "Parameter 2: $param2"
}

# Call the function with parameters
my_function_with_parameters "value1" "value2"

Complex Function (with processing and multiple parameters)

my_complex_function() {
    name=$1
    age=$2

    if [ "$age" -lt 18 ]; then
        echo "$name is a minor."
    else
        echo "$name is an adult."
    fi
}

# Call the complex function
my_complex_function "Alice" 20
my_complex_function "Bob" 15

9. Variable Testing

Comparators for Tests

  • String Comparison:
      – Equal: ==
      – Not equal: !=
      – Less than: <
      – Greater than: >

Example:

if [ "$string1" == "$string2" ]; then
    echo "The strings are identical"
fi
  • Numeric Comparison:
      – Equal: -eq
      – Not equal: -ne
      – Less than: -lt
      – Greater than: -gt
      – Less than or equal: -le
      – Greater than or equal: -ge

Example:

if [ "$number1" -lt "$number2" ]; then
    echo "$number1 is less than $number2"
fi

10. Loops

Use for, while, or until loops to iterate:

for i in {1..5}; do
    echo $i
done

11. Error Handling

Check for errors with $? and use set -e to stop the script in case of an error:

set -e

12. Using set

  • Use set -u to treat undefined variables as errors:
set -u

13. Output

Use echo to display messages or results:

echo "Message"

14. Using trap

Use trap to handle signals and clean up before exiting:

trap 'cleanup_command' EXIT

15. Best Practices

  • Avoid ambiguous variable names.
  • Use descriptive file names.
  • Test your scripts in a safe environment before running them in production.

Similar Posts