Environment Isolation: local and readonly
By default, all variables defined inside Bash functions are global. If a user triggers a function that accidentally overwrites a critical system variable used elsewhere in the script, it can break your logic or open vulnerabilities.
- Always declare variables inside functions as local.
- Use readonly for configuration variables (like your project directory path) so they cannot be altered or hijacked later in the script execution.
# Protect your configuration constants
readonly PROJECT_DIR="/opt/my_project"
my_function() {
# Isolate this variable to this function block only
local user_arg="$1"
echo "Processing $user_arg inside $PROJECT_DIR"
}