format your shell script automatically
To create a shell script that converts another shell script into a well-formatted one, we can use the awk
command, a powerful text-processing tool. This script will help you format and clean up the indentation of the input shell script. Here’s the shell script:
#!/bin/bash # Check if the user provided the input filename if [ $# -lt 1 ]; then echo "Usage: $0 <input_script.sh>" exit 1 fi input_script="$1" output_script="${input_script%.sh}_formatted.sh" # Check if the input file exists if [ ! -f "$input_script" ]; then echo "Error: Input file not found!" exit 1 fi # Formatting the script using awk awk 'BEGIN { indent = 0 } { # Remove leading/trailing whitespaces gsub(/^[ \t]+|[ \t]+$/, "") # Handle opening curly braces if (/then$|do$|else$|elif.*$|fi$|case.*$|then.*$|do.*$|esac.*$/) { print_indent() indent += 2 } else if (/^\}[ \t]*else/) { # Handle "} else" case indent -= 2 print_indent() indent += 2 } else if (/^\}[ \t]*fi/) { # Handle "} fi" case indent -= 2 print_indent() } else if (/^\}[ \t]*;;/) { # Handle "} ;;" case indent -= 2 print_indent() } print_indent() print # Handle closing curly braces if (/^\}/) { indent -= 2 } } END { # Print any remaining indent level print_indent() } function print_indent() { for (i = 0; i < indent; i++) { printf " " } }' "$input_script" > "$output_script" echo "Formatted script saved to: $output_script"