Shell Script by Example: Variables
Master Bash variable handling with this sample code demonstrating assignment syntax without spaces, variable expansion using dollar sign, readonly constants, the unset command, and export for creating environment variables accessible to child processes.
Code
#!/bin/bash
# Assignment (no spaces around =)
name="World"
count=10
# Accessing variables (use $)
echo "Hello, $name!"
# Read-only variables
readonly PI=3.14
# PI=3.14159 # This would cause an error
# Unsetting variables
unset name
echo "Name is now: $name" # Prints empty string
# Environment variables (exported to child processes)
export MY_ENV_VAR="Production"Explanation
In shell scripting, variables are untyped and stored as strings by default. Assignment requires no spaces around the equals sign; if you add spaces, the shell interprets the variable name as a command name, causing errors. To access a variable's value, prefix its name with a dollar sign $. The ${var} form is more reliable for complex scenarios like string interpolation or when the variable name is adjacent to other text.
Variables are mutable by default, but you can make them immutable using the readonly command, which is useful for defining constants. Attempting to modify a readonly variable results in an error. The unset command removes a variable entirely from the shell's memory. Accessing an unset or undefined variable typically returns an empty string rather than throwing an error, which can lead to subtle bugs if not handled carefully.
By default, variables are local to the current shell session and not inherited by child processes or subshells. To make a variable available to child processes, you must export it, creating an environment variable. Environment variables provide flexibility and reusability, allowing scripts to adapt to different environments without hardcoding values. Conventionally, environment variables use UPPERCASE names, while local script variables use lowercase to distinguish them visually.
Best practices include always quoting variables to prevent word splitting and globbing issues, especially when values might contain spaces or special characters. Use local within functions to prevent variable pollution and unintended side effects. For sensitive data like API keys, consider using environment variables rather than em in scripts, though be aware that environment variables can be accessed by other processes running under the same user.
Code Breakdown
name="World" assigns value with no spaces around the equals sign.$name expands to the variable's value for use in commands.readonly PI makes the variable immutable, preventing reassignment.export MY_ENV_VAR makes the variable available to child processes.
