-
Notifications
You must be signed in to change notification settings - Fork 0
Bash Coding Standard
Adam Szablya edited this page Jun 2, 2024
·
1 revision
Metrolla has adopted the Google Coding Standard for Bash scripts.
Google's style guide for Bash scripting emphasizes writing clean, maintainable, and portable shell scripts. Below is a summary of the key points from the guide:
- Clarity: Write clear and understandable scripts.
- Consistency: Follow established coding conventions and structures.
- Portability: Ensure scripts are portable across different environments.
- Use
#!/bin/bashfor Bash scripts.#!/bin/bash
- Use
.shas the file extension for shell scripts.
- Use comments to explain the purpose of the script, significant sections, and complex logic.
# This script calculates the sum of two numbers.
-
Indentation: Use 2 spaces for indentation. Avoid tabs.
if [ "$condition" ]; then echo "Condition met" fi
- Line Length: Limit lines to 80 characters.
- Line Breaks: Use line breaks to separate logical sections of the script.
-
Naming: Use
lower_snake_casefor variable names. -
Initialization: Always initialize variables.
my_variable="value" -
Readonly Variables: Use
readonlyfor constants.readonly MY_CONSTANT="constant_value"
-
Double Quotes: Use double quotes to prevent word splitting and globbing.
my_var="some value" echo "$my_var"
-
Single Quotes: Use single quotes for literals that don't need variable interpolation.
echo 'Literal string'
- Use
[(also known astest) for testing conditions, with spaces around the brackets.if [ "$var" -eq 1 ]; then echo "Variable equals 1" fi
- Define functions using
functionkeyword. - Use
lower_snake_casefor function names. - Place all function definitions at the start of the script.
function my_function { echo "Function body" }
- Use
set -eto exit on error. - Use
set -uto treat unset variables as an error. - Use
trapto clean up temporary files and handle signals.set -e set -u trap 'rm -f /tmp/my_temp_file' EXIT function cleanup { rm -f /tmp/my_temp_file } trap cleanup EXIT
- Use
readfor input. - Use
echofor output.read -p "Enter your name: " name echo "Hello, $name"
- Structure scripts with the following sections:
- Shebang
- Comments and License Information
- Imports and Global Variables
- Functions
- Main Script Execution
- Avoid using Bash-specific features if possible.
- Prefer POSIX-compliant code for better portability.
Here is an example that illustrates some of these standards:
#!/bin/bash
# This script demonstrates a simple greeting.
# Constants
readonly SCRIPT_NAME=$(basename "$0")
# Function to print usage
function print_usage {
echo "Usage: $SCRIPT_NAME <name>"
}
# Main function
function main {
if [ "$#" -ne 1 ]; then
print_usage
exit 1
fi
local name="$1"
echo "Hello, $name"
}
# Script entry point
main "$@"For the most detailed and up-to-date information, refer to the full Google Shell Style Guide.