-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlab49_advanced_shell_scripting.txt
More file actions
1738 lines (1400 loc) · 47.5 KB
/
lab49_advanced_shell_scripting.txt
File metadata and controls
1738 lines (1400 loc) · 47.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
RHCE RH254 HANDS-ON LAB: ADVANCED SHELL SCRIPTING
===============================================
LAB OBJECTIVE:
Master advanced shell scripting techniques including complex functions, error handling, signal processing, advanced parameter handling, and enterprise-grade script development
PREREQUISITES:
- RHEL 8/9 system with root access
- Understanding of basic shell scripting
- Knowledge of Linux system administration
- Familiarity with command-line tools
LAB SCENARIO:
Develop enterprise-grade shell scripts with advanced features including robust error handling, logging, configuration management, and automated system administration tasks.
EQUIPMENT NEEDED:
- RHEL system (192.168.1.20)
- Text editor (vim/nano)
- Various system utilities for script testing
LAB TASKS:
PART A: ADVANCED SCRIPT STRUCTURE AND FUNCTIONS
------------------------------------------------
1. Create advanced script template:
# mkdir -p /opt/scripts/{templates,functions,configs,logs}
# vim /opt/scripts/templates/advanced-script-template.sh
#!/bin/bash
#
# Advanced Shell Script Template
# Author: System Administrator
# Version: 1.0
# Description: Enterprise-grade script template with advanced features
#
# Script metadata
readonly SCRIPT_NAME="$(basename "$0")"
readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly SCRIPT_VERSION="1.0"
readonly SCRIPT_AUTHOR="System Administrator"
# Configuration
CONFIG_FILE="${SCRIPT_DIR}/../configs/${SCRIPT_NAME%.sh}.conf"
readonly LOG_FILE="/var/log/${SCRIPT_NAME%.sh}.log"
readonly PID_FILE="/var/run/${SCRIPT_NAME%.sh}.pid"
# Ensure required directories exist
mkdir -p "$(dirname "$LOG_FILE")" "$(dirname "$PID_FILE")"
# Global variables
DEBUG=false
VERBOSE=false
DRY_RUN=false
FORCE=false
# Color codes for output
readonly RED='\033[0;31m'
readonly GREEN='\033[0;32m'
readonly YELLOW='\033[1;33m'
readonly BLUE='\033[0;34m'
readonly NC='\033[0m' # No Color
# Logging functions
log_message() {
local level="$1"
local message="$2"
local timestamp
timestamp=$(date '+%Y-%m-%d %H:%M:%S')
echo "[$timestamp] [$level] $message" >> "$LOG_FILE"
case "$level" in
"ERROR")
echo -e "${RED}[ERROR]${NC} $message" >&2
;;
"WARN")
echo -e "${YELLOW}[WARN]${NC} $message" >&2
;;
"INFO")
[ "$VERBOSE" = true ] && echo -e "${GREEN}[INFO]${NC} $message"
;;
"DEBUG")
[ "$DEBUG" = true ] && echo -e "${BLUE}[DEBUG]${NC} $message"
;;
esac
}
log_error() { log_message "ERROR" "$1"; }
log_warn() { log_message "WARN" "$1"; }
log_info() { log_message "INFO" "$1"; }
log_debug() { log_message "DEBUG" "$1"; }
# Error handling
error_exit() {
log_error "$1"
cleanup
exit "${2:-1}"
}
# Signal handling
cleanup() {
log_info "Cleaning up..."
[ -f "$PID_FILE" ] && rm -f "$PID_FILE"
}
signal_handler() {
local signal="$1"
log_warn "Received signal: $signal"
cleanup
exit 130
}
# Set up signal traps
trap 'signal_handler INT' INT
trap 'signal_handler TERM' TERM
trap 'cleanup' EXIT
# Usage function
usage() {
cat << EOF
Usage: $SCRIPT_NAME [OPTIONS] [ARGUMENTS]
DESCRIPTION:
Advanced shell script template with enterprise features
OPTIONS:
-h, --help Show this help message
-v, --verbose Enable verbose output
-d, --debug Enable debug output
-n, --dry-run Show what would be done without executing
-f, --force Force execution without prompts
-c, --config FILE Use custom configuration file
-V, --version Show version information
EXAMPLES:
$SCRIPT_NAME --verbose
$SCRIPT_NAME --config /path/to/config.conf
$SCRIPT_NAME --dry-run --debug
EOF
}
# Version information
version_info() {
cat << EOF
$SCRIPT_NAME version $SCRIPT_VERSION
Author: $SCRIPT_AUTHOR
EOF
}
# Configuration loading
load_config() {
local config_file="${1:-$CONFIG_FILE}"
if [ -f "$config_file" ]; then
log_debug "Loading configuration from: $config_file"
# shellcheck source=/dev/null
source "$config_file"
else
log_warn "Configuration file not found: $config_file"
fi
}
# Parameter validation
validate_parameters() {
return 0
}
# Main function
main() {
log_info "Starting $SCRIPT_NAME v$SCRIPT_VERSION"
# Create PID file
echo "$$" > "$PID_FILE" || error_exit "Unable to create PID file"
# Load configuration
load_config
# Validate parameters
validate_parameters || error_exit "Parameter validation failed"
# Main script logic goes here
log_info "Main script execution completed"
}
# Parameter parsing
while [[ $# -gt 0 ]]; do
case $1 in
-h|--help)
usage
exit 0
;;
-v|--verbose)
VERBOSE=true
shift
;;
-d|--debug)
DEBUG=true
VERBOSE=true
shift
;;
-n|--dry-run)
DRY_RUN=true
shift
;;
-f|--force)
FORCE=true
shift
;;
-c|--config)
CONFIG_FILE="$2"
shift 2
;;
-V|--version)
version_info
exit 0
;;
-*)
error_exit "Unknown option: $1"
;;
*)
break
;;
esac
done
# Execute main function
main "$@"
// Errors present which got fixed in script (in comparision to old script):
// - readonly CONFIG_FILE was reassigned later → runtime error
// - Log and PID directories may not exist → redirection failure
// - PID file write can fail silently
// - Shellcheck-level robustness (safe sourcing, quoting)
2. Create advanced function library:
# vim /opt/scripts/functions/advanced-functions.sh
#!/bin/bash
#
# Advanced Shell Functions Library
# Collection of reusable functions for enterprise scripts
#
# Safe defaults if main script did not define them
: "${FORCE:=false}"
: "${DRY_RUN:=false}"
# Dummy log functions if not sourced from main template
log_debug() { :; }
log_info() { :; }
log_warn() { echo "[WARN] $*" >&2; }
log_error() { echo "[ERROR] $*" >&2; }
# Check if running as root
require_root() {
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root" >&2
exit 1
fi
}
# Check if command exists
command_exists() {
command -v "$1" >/dev/null 2>&1
}
# Prompt for confirmation
confirm() {
local prompt="${1:-Are you sure?}"
local default="${2:-n}"
local response
if [ "$FORCE" = true ]; then
return 0
fi
while true; do
read -r -p "$prompt [y/N]: " response || return 1
response=${response:-$default}
case "$response" in
[Yy]|[Yy][Ee][Ss])
return 0
;;
[Nn]|[Nn][Oo])
return 1
;;
*)
echo "Please answer yes or no."
;;
esac
done
}
# Execute command with logging
execute_command() {
local cmd="$1"
local description="${2:-Executing command}"
log_debug "$description: $cmd"
if [ "$DRY_RUN" = true ]; then
log_info "[DRY RUN] Would execute: $cmd"
return 0
fi
if eval "$cmd"; then
log_info "$description: SUCCESS"
return 0
else
local exit_code=$?
log_error "$description: FAILED (exit code: $exit_code)"
return "$exit_code"
fi
}
# Retry function with exponential backoff
retry_with_backoff() {
local max_attempts="$1"
local delay="$2"
local command="$3"
local attempt=1
while [ "$attempt" -le "$max_attempts" ]; do
log_debug "Attempt $attempt of $max_attempts: $command"
if eval "$command"; then
log_info "Command succeeded on attempt $attempt"
return 0
fi
if [ "$attempt" -eq "$max_attempts" ]; then
log_error "Command failed after $max_attempts attempts"
return 1
fi
log_warn "Attempt $attempt failed, retrying in ${delay}s..."
sleep "$delay"
delay=$((delay * 2))
attempt=$((attempt + 1))
done
}
# Progress bar function
progress_bar() {
local current="$1"
local total="$2"
local width="${3:-50}"
local prefix="${4:-Progress}"
[ "$total" -eq 0 ] && return 1
local percentage=$((current * 100 / total))
local completed=$((current * width / total))
local remaining=$((width - completed))
printf "\r%s: [" "$prefix"
printf "%*s" "$completed" | tr ' ' '='
printf "%*s" "$remaining" | tr ' ' '-'
printf "] %d%% (%d/%d)" "$percentage" "$current" "$total"
if [ "$current" -eq "$total" ]; then
echo
fi
}
# File backup function
backup_file() {
local file="$1"
local backup_dir="${2:-/tmp/backups}"
if [ ! -f "$file" ]; then
log_error "File not found: $file"
return 1
fi
mkdir -p "$backup_dir" || return 1
local backup_file
backup_file="$backup_dir/$(basename "$file").$(date +%Y%m%d_%H%M%S).bak"
if cp "$file" "$backup_file"; then
log_info "File backed up: $file -> $backup_file"
echo "$backup_file"
return 0
else
log_error "Failed to backup file: $file"
return 1
fi
}
# Network connectivity check
check_connectivity() {
local host="${1:-8.8.8.8}"
local timeout="${2:-5}"
if ping -c 1 -W "$timeout" "$host" >/dev/null 2>&1; then
log_debug "Network connectivity to $host: OK"
return 0
else
log_warn "Network connectivity to $host: FAILED"
return 1
fi
}
# Service management functions
ensure_service_running() {
local service="$1"
if systemctl is-active "$service" >/dev/null 2>&1; then
log_debug "Service $service is already running"
return 0
fi
log_info "Starting service: $service"
if systemctl start "$service"; then
log_info "Service $service started successfully"
return 0
else
log_error "Failed to start service: $service"
return 1
fi
}
# Disk space check
check_disk_space() {
local path="${1:-/}"
local threshold="${2:-90}"
local usage
usage=$(df -P "$path" | awk 'END {gsub(/%/, "", $5); print $5}')
if [ "$usage" -gt "$threshold" ]; then
log_warn "Disk usage for $path is ${usage}% (threshold: ${threshold}%)"
return 1
else
log_debug "Disk usage for $path is ${usage}% (OK)"
return 0
fi
}
# Array manipulation functions
array_contains() {
local element="$1"
shift
local array=("$@")
for item in "${array[@]}"; do
if [ "$item" = "$element" ]; then
return 0
fi
done
return 1
}
# String manipulation functions
trim_whitespace() {
local string="$1"
echo "$string" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//'
}
# Configuration file parsing
parse_config_value() {
local config_file="$1"
local key="$2"
local default_value="${3:-}"
if [ -f "$config_file" ]; then
local value
value=$(grep -E "^${key}=" "$config_file" | cut -d'=' -f2- | tr -d '"' | tr -d "'")
echo "${value:-$default_value}"
else
echo "$default_value"
fi
}
// Errors present which got fixed in script (in comparision to old script):
// - Functions depend on log_* variables → fail if not sourced
// - FORCE, DRY_RUN may be unset → [ "$VAR" = true ] errors
// - df | tail -1 can break on localized output
// - Arithmetic comparisons need numeric safety
// - read -p must handle non-interactive shells
// - Quoting & defensive checks
PART B: ERROR HANDLING AND DEBUGGING
-------------------------------------
1. Create error handling framework:
# vim /opt/scripts/functions/error-handling.sh
#!/bin/bash
#
# Advanced Error Handling Framework
#
# Safe defaults if not defined by caller
: "${DEBUG:=false}"
# Dummy logging & cleanup functions if not sourced
log_error() { echo "[ERROR] $*" >&2; }
log_warn() { echo "[WARN] $*" >&2; }
cleanup() { :; }
# Error codes
readonly E_SUCCESS=0
readonly E_GENERAL=1
readonly E_MISUSE=2
readonly E_NOEXEC=126
readonly E_NOTFOUND=127
readonly E_INVALID_ARG=128
readonly E_FATAL=130
# Error tracking
ERROR_COUNT=0
WARNING_COUNT=0
# Stack trace function
print_stack_trace() {
local frame=0
echo "Stack trace:" >&2
while caller "$frame" >&2; do
((frame++))
done
}
# Enhanced error exit
die() {
local exit_code="${1:-$E_GENERAL}"
local message="${2:-An error occurred}"
log_error "$message"
if [ "$DEBUG" = true ]; then
print_stack_trace
fi
cleanup
exit "$exit_code"
}
# Error accumulator
add_error() {
local message="$1"
ERROR_COUNT=$((ERROR_COUNT + 1))
log_error "Error #$ERROR_COUNT: $message"
}
add_warning() {
local message="$1"
WARNING_COUNT=$((WARNING_COUNT + 1))
log_warn "Warning #$WARNING_COUNT: $message"
}
# Check for accumulated errors
check_errors() {
if [ "$ERROR_COUNT" -gt 0 ]; then
die "$E_GENERAL" "Script completed with $ERROR_COUNT error(s) and $WARNING_COUNT warning(s)"
elif [ "$WARNING_COUNT" -gt 0 ]; then
log_warn "Script completed with $WARNING_COUNT warning(s)"
fi
}
# Assertion function
assert() {
local condition="$1"
local message="${2:-Assertion failed}"
if ! eval "$condition"; then
die "$E_GENERAL" "ASSERTION FAILED: $message"
fi
}
# Try-catch simulation
try() {
local command="$1"
local error_handler="${2:-}"
if ! eval "$command"; then
local exit_code=$?
if [ -n "$error_handler" ]; then
eval "$error_handler $exit_code"
else
add_error "Command failed: $command (exit code: $exit_code)"
fi
return "$exit_code"
fi
return 0
}
// Errors present which got fixed in script (in comparision to old script):
// - log_error, log_warn, cleanup, DEBUG may be undefined
//- [ "$DEBUG" = true ] fails if DEBUG unset
// - Arithmetic comparisons without quotes (shellcheck)
// - Library should not break if sourced alone
2. Create debugging utilities:
# vim /opt/scripts/functions/debug-utils.sh
#!/bin/bash
#
# Debugging Utilities
#
# Safe defaults
: "${DEBUG:=false}"
# Dummy logger if not defined
log_debug() { :; }
# Debug trace
debug_trace() {
if [ "$DEBUG" = true ]; then
echo "DEBUG: ${BASH_SOURCE[1]}:${BASH_LINENO[0]} ${FUNCNAME[1]}()" >&2
fi
}
# Variable dumper
dump_vars() {
local prefix="${1:-}"
if [ "$DEBUG" = true ]; then
echo "=== Variable Dump ===" >&2
if [ -n "$prefix" ]; then
set | grep "^$prefix" >&2
else
set >&2
fi
echo "===================" >&2
fi
}
# Function call tracer
trace_calls() {
if [ "$DEBUG" = true ]; then
set -x
fi
}
stop_trace() {
set +x
}
# Performance timing
start_timer() {
TIMER_START=$(date +%s.%N)
}
end_timer() {
local label="${1:-Operation}"
local end_time
local duration
end_time=$(date +%s.%N)
if command -v bc >/dev/null 2>&1 && [ -n "${TIMER_START:-}" ]; then
duration=$(echo "$end_time - $TIMER_START" | bc)
log_debug "$label took ${duration}s"
fi
}
# Memory usage tracker
check_memory_usage() {
local process_name="${1:-$$}"
local memory_kb
memory_kb=$(ps -o rss= -p "$process_name" 2>/dev/null)
if [ -n "$memory_kb" ]; then
local memory_mb=$((memory_kb / 1024))
log_debug "Memory usage: ${memory_mb}MB"
fi
}
// Errors fixed in script (in comparision to old script):
// -DEBUG, log_debug, TIMER_START may be unset
// -bc dependency not validated
// -Arithmetic without guarding
// -Library must not crash when sourced alone
PART C: ADVANCED PARAMETER HANDLING
------------------------------------
1. Create parameter processing framework:
# vim /opt/scripts/functions/parameter-handling.sh
#!/bin/bash
#
# Advanced Parameter Handling Framework
#
# Safe fallback logger if main framework not sourced
log_debug() { :; }
# Safe fallback for config parsing if not sourced
parse_config_value() { :; }
# Parameter validation functions
validate_integer() {
local value="$1"
local min="${2:-}"
local max="${3:-}"
if ! [[ "$value" =~ ^[0-9]+$ ]]; then
return 1
fi
if [ -n "$min" ] && [ "$value" -lt "$min" ]; then
return 1
fi
if [ -n "$max" ] && [ "$value" -gt "$max" ]; then
return 1
fi
return 0
}
validate_email() {
local email="$1"
local regex="^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
if [[ "$email" =~ $regex ]]; then
return 0
else
return 1
fi
}
validate_ip_address() {
local ip="$1"
local regex="^([0-9]{1,3}\.){3}[0-9]{1,3}$"
if [[ "$ip" =~ $regex ]]; then
IFS='.' read -ra octets <<< "$ip"
for octet in "${octets[@]}"; do
if [ "$octet" -gt 255 ]; then
return 1
fi
done
return 0
else
return 1
fi
}
validate_file_path() {
local path="$1"
local must_exist="${2:-false}"
if [ "$must_exist" = true ] && [ ! -e "$path" ]; then
return 1
fi
if [[ "$path" =~ ^[a-zA-Z0-9/_.-]+$ ]]; then
return 0
else
return 1
fi
}
# Advanced option parsing
parse_long_options() {
local args=("$@")
local parsed_args=()
for arg in "${args[@]}"; do
case "$arg" in
--*=*)
local option="${arg%%=*}"
local value="${arg#*=}"
parsed_args+=("$option" "$value")
;;
--*)
parsed_args+=("$arg")
;;
*)
parsed_args+=("$arg")
;;
esac
done
echo "${parsed_args[@]}"
}
# Configuration file parameter override
override_with_config() {
local config_file="$1"
shift
local variables=("$@")
if [ -f "$config_file" ]; then
for var in "${variables[@]}"; do
local value
value=$(parse_config_value "$config_file" "$var")
if [ -n "$value" ]; then
declare -g "$var"="$value"
log_debug "Override from config: $var=$value"
fi
done
fi
}
# Environment variable parameter override
override_with_env() {
local prefix="$1"
shift
local variables=("$@")
for var in "${variables[@]}"; do
local env_var="${prefix}_${var^^}"
if [ -n "${!env_var:-}" ]; then
declare -g "$var"="${!env_var}"
log_debug "Override from environment: $var=${!env_var}"
fi
done
}
// Errors present which got fixed in script (in comparision to old script):
// -log_debug may be undefined
// -parse_config_value may be undefined
// -declare -g must not break older shells (safe usage)
// -Unquoted command substitutions
// -Defensive defaults so the library is safe when sourced alon
2. Create configuration management system:
# vim /opt/scripts/functions/config-management.sh
#!/bin/bash
#
# Configuration Management System
#
# Safe fallback loggers if main framework not sourced
log_info() { :; }
log_error() { echo "[ERROR] $*" >&2; }
# Safe fallback for config parsing
parse_config_value() { :; }
# Configuration file template generator
generate_config_template() {
local config_file="$1"
local script_name="${2:-$(basename -- "$0" .sh)}"
# Ensure target directory exists
mkdir -p "$(dirname "$config_file")" || return 1
cat > "$config_file" << EOF
# Configuration file for $script_name
# Generated on $(date)
# General settings
DEBUG=false
VERBOSE=false
LOG_LEVEL=INFO
# Paths
LOG_DIR=/var/log
TEMP_DIR=/tmp
BACKUP_DIR=/backup
# Network settings
TIMEOUT=30
RETRY_COUNT=3
# Email notifications
ENABLE_EMAIL=false
ADMIN_EMAIL=admin@example.com
SMTP_SERVER=localhost
# Custom settings (add your own below)
# CUSTOM_SETTING=value
EOF
log_info "Configuration template created: $config_file"
}
# Configuration validation
validate_config() {
local config_file="$1"
shift
local required_vars=("$@")
if [ ! -f "$config_file" ]; then
log_error "Configuration file not found: $config_file"
return 1
fi
local missing_vars=()
for var in "${required_vars[@]}"; do
local value
value=$(parse_config_value "$config_file" "$var")
if [ -z "$value" ]; then
missing_vars+=("$var")
fi
done
if [ "${#missing_vars[@]}" -gt 0 ]; then
log_error "Missing required configuration variables: ${missing_vars[*]}"
return 1
fi
return 0
}
# Dynamic configuration reloading
reload_config() {
local config_file="$1"
if [ -f "$config_file" ]; then
log_info "Reloading configuration from: $config_file"
# shellcheck source=/dev/null
source "$config_file"
return 0
else
log_error "Cannot reload config, file not found: $config_file"
return 1
fi
}
// Errors which got fixed in script (in comparision to old script):
// - log_info, log_error may be undefined
// - parse_config_value may be undefined
// - source "$config_file" can break shellcheck / strict shells
// - cat > "$config_file" fails if directory doesn’t exist
// - Array handling needed defensive quoting
PART D: SYSTEM ADMINISTRATION SCRIPTS
--------------------------------------
1. Create system monitoring script:
# vim /opt/scripts/system-monitor.sh
#!/bin/bash
#
# Advanced System Monitoring Script
#
# Source function libraries
source /opt/scripts/functions/advanced-functions.sh
source /opt/scripts/functions/error-handling.sh
source /opt/scripts/functions/debug-utils.sh
source /opt/scripts/templates/advanced-script-template.sh 2>/dev/null || true
# Safe defaults
log_info() { :; }
log_debug() { :; }
log_warn() { echo "[WARN] $*" >&2; }
log_error() { echo "[ERROR] $*" >&2; }
load_config() { :; }
# Script configuration
readonly SCRIPT_NAME="system-monitor"
readonly CONFIG_FILE="/opt/scripts/configs/system-monitor.conf"
readonly LOG_FILE="/var/log/system-monitor.log"
mkdir -p "$(dirname "$LOG_FILE")"
# Default thresholds
CPU_THRESHOLD=80
MEMORY_THRESHOLD=85
DISK_THRESHOLD=90
LOAD_THRESHOLD=2.0
# Monitoring functions
check_cpu_usage() {
local cpu_usage
cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1 | cut -d'.' -f1)
log_debug "CPU usage: ${cpu_usage}%"
if [ "$cpu_usage" -gt "$CPU_THRESHOLD" ]; then
add_warning "High CPU usage: ${cpu_usage}% (threshold: ${CPU_THRESHOLD}%)"
log_info "Top CPU processes:"
ps aux --sort=-%cpu | head -6 | tail -5
fi
echo "$cpu_usage"
}
check_memory_usage() {
local memory_usage
memory_usage=$(free | awk '/Mem:/ {printf("%.0f", $3/$2 * 100)}')
log_debug "Memory usage: ${memory_usage}%"
if [ "$memory_usage" -gt "$MEMORY_THRESHOLD" ]; then
add_warning "High memory usage: ${memory_usage}% (threshold: ${MEMORY_THRESHOLD}%)"
log_info "Top memory processes:"
ps aux --sort=-%mem | head -6 | tail -5
fi
echo "$memory_usage"
}
check_disk_usage() {