DEV Community

Cover image for My Coding Rules for Bash Scripts
Frederic Delorme
Frederic Delorme

Posted on

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
Enter fullscreen mode Exit fullscreen mode

2. Permissions

Ensure that the script has execution permissions:

chmod +x script_name.sh
Enter fullscreen mode Exit fullscreen mode

3. Comments

Use comments to explain the code:

# This is a comment
Enter fullscreen mode Exit fullscreen mode

4. Variables

Variable Declaration

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

Variable Processing

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

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

8. Functions

Function Examples

Simple Function (no parameters)

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

# Call the function
my_simple_function
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
  • 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
Enter fullscreen mode Exit fullscreen mode

10. Loops

Use for, while, or until loops to iterate:

for i in {1..5}; do
    echo $i
done
Enter fullscreen mode Exit fullscreen mode

11. Error Handling

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

set -e
Enter fullscreen mode Exit fullscreen mode

12. Using set

  • Use set -u to treat undefined variables as errors:
set -u
Enter fullscreen mode Exit fullscreen mode

13. Output

Use echo to display messages or results:

echo "Message"
Enter fullscreen mode Exit fullscreen mode

14. Using trap

Use trap to handle signals and clean up before exiting:

trap 'cleanup_command' EXIT
Enter fullscreen mode Exit fullscreen mode

15. Best Practices

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

Top comments (0)