Advanced Bash Scripting

Conventions

Variables

Proper variable management in Bash scripts improves readability, prevents accidental overwrites, and makes your code easier to maintain. In this guide, you’ll learn best practices for naming variables, defining constants, and exporting values for child processes.


Table of Contents


1. Naming Conventions

Follow these guidelines to create clear, self-documenting variable names:

ConventionDescriptionExample
LowercaseAll variable names in lowercase to avoid conflictsusername="alice"
Snake caseUse underscores for multi-word namesfirst_name_last_name="Alice"
Descriptive namesReflect the variable’s purposeconfig_file="/etc/app.conf"
Single-letter (optional)Only for simple counters or arithmetic operationsx=10

Example:

first_name_last_name="Alice"
source_file="/etc/config.yaml"
count=42
x=10

Note

Avoid uppercase names for regular variables—uppercase is conventionally reserved for constants (see Defining Constants).


2. Defining Constants

When you have values that should never change, define them in uppercase snake_case and mark them as read-only:

readonly FILE_NAME="file.txt"
readonly MAX_RETRIES=5
readonly PI=3.14159

Using readonly serves two purposes:

  1. Clarity: Signals to readers that these values are fixed.
  2. Safety: Prevents accidental reassignment later in the script.

Warning

Attempting to modify a readonly variable will produce an error:

PI=3.14   # bash: PI: readonly variable

3. Exporting Variables

Export variables when you need them in child processes, subshells, or external scripts.

Export an existing variable

source_file="/etc/config.yaml"
export source_file

Define and export in one step

export HOME_DIR="/home/user"

Exported variables become part of the environment for all subsequent commands and processes started from the current shell.


4. References

Watch Video

Watch video content

Previous
Overview