#!/usr/bin/env bash# Interactive generator that scaffolds a new, executable Bash script with standard headers and strict error handling flags.set-euopipefail
# Prompt user for the filenameread-rp"Enter desired script name (e.g. system-cleanup): "raw_filename
# Sanitize input: replace spaces with hyphens, remove invalid characters, strip trailing .shbase_name=$(echo"${raw_filename%.sh}"|tr-s' ''-'|tr-cd'[:alnum:]_-')# Check if input resulted in an empty string after sanitizationif[[-z"$base_name"]];thenecho"Error: Filename cannot be empty or contain only invalid characters.">&2exit1fifilename="${base_name}.sh"# Check if the file already existsif[[-f"$filename"]];thenread-rp"File '$filename' already exists. Overwrite? (y/N): "overwrite
if[[!"$overwrite"=~^[yY]$]];thenecho"Operation canceled. Exiting."exit0fifi# Write shebang and production-grade script header# Using unquoted EOF to inject variables during creation, escaping runtime variables like \$EUIDcat<<EOF >"$filename"#!/usr/bin/env bash# ==============================================================================# Script Name: $filename# Description: # Created: $(date +%Y-%m-%d)# ==============================================================================# Exit immediately on error, unset variable, or piped command failureset -euo pipefail# Require root privileges (Uncomment if needed)# if [[ "\$EUID" -ne 0 ]]; then# echo "Error: This script must be run as root or via sudo." >&2# exit 1# fiEOF# Make the new script executablechmod+x"$filename"echo"--------------------------------------------------"echo"Success: Created executable script '$filename'"echo"Path: $(pwd)/$filename"echo"--------------------------------------------------"# Automatically open the generated scriptifcommand-vsubl&>/dev/null;thensubl"$filename"elif[[-n"${EDITOR:-}"]];then"$EDITOR""$filename"fi