#!/bin/bash # Mission Statement: # This script displays the contents of specified files with formatted headers. # It provides optional file size limits through the -k flag (specified in KB). # Without the -k flag, files are shown in their entirety. # With -k flag, files larger than the specified size are truncated with a warning. # The script handles both Linux and MacOS systems using compatible stat commands. # Color output is available via the -c flag for better visual organization. # ANSI color codes BLUE='\033[0;34m' GREEN='\033[0;32m' RED='\033[0;31m' NC='\033[0m' # No Color usage() { echo "Usage: $(basename $0) [-k size_in_kb] [-c] files..." echo " -k: Maximum file size in KB (optional)" echo " -c: Enable color output" exit 1 } # Initialize variables COLOR=false MAX_SIZE_KB="" # Parse command line options while getopts "k:c" opt; do case $opt in k) MAX_SIZE_KB="$OPTARG";; c) COLOR=true;; ?) usage;; esac done # Shift past the options shift $((OPTIND-1)) # Check if any files were specified if [ $# -eq 0 ]; then usage fi # Get file size in KB (compatible with both Linux and MacOS) get_file_size() { if [[ "$OSTYPE" == "darwin"* ]]; then stat -f %z "$1" else stat --format=%s "$1" fi } # Format and display file header show_header() { local file="$1" local size_bytes=$(get_file_size "$file") local size_kb=$((size_bytes / 1024)) if $COLOR; then echo -e "\n${BLUE}=== File: ${GREEN}$file${BLUE} (${size_kb}KB) ===${NC}" else echo -e "\n=== File: $file (${size_kb}KB) ===" fi } # Process each file for file in "$@"; do if [ ! -f "$file" ]; then if $COLOR; then echo -e "${RED}Error: '$file' does not exist or is not a regular file${NC}" >&2 else echo "Error: '$file' does not exist or is not a regular file" >&2 fi continue fi show_header "$file" if [ -n "$MAX_SIZE_KB" ]; then size_bytes=$(get_file_size "$file") size_kb=$((size_bytes / 1024)) if [ $size_kb -gt $MAX_SIZE_KB ]; then if $COLOR; then echo -e "${RED}File size ($size_kb KB) exceeds limit ($MAX_SIZE_KB KB). Showing first $MAX_SIZE_KB KB:${NC}" else echo "File size ($size_kb KB) exceeds limit ($MAX_SIZE_KB KB). Showing first $MAX_SIZE_KB KB:" fi head -c $((MAX_SIZE_KB * 1024)) "$file" echo -e "\n[Truncated...]" else cat "$file" fi else cat "$file" fi done