Anyone using AI to generate scripts? Is using AI effective?
This TCL memory check script was AI generated and only had one error. See the commented out lines. Not a bad effort by Mr. AI.
regexp match variables not allowed when using -inline
while executing
"regexp -inline -line {^MemTotal:\s+(\d+)} $memdata {}"
(procedure "check_memory" line 7)
invoked from within
"check_memory"
("while" body line 2)
invoked from within
"while {1} {
check_memory
after 60000 ;# Wait 60,000 ms (60 seconds)
}"
(file "./check_memory.tcl" line 43)
#!/usr/bin/env tclsh
proc check_memory {} {
# Parse memory usage from /proc/meminfo
set meminfo [open "/proc/meminfo" r]
set memdata [read $meminfo]
close $meminfo
# set memtotal [regexp -inline -line {^MemTotal:\s+(\d+)} $memdata {}]
set memtotal [regexp -inline -line {^MemTotal:\s+(\d+)} $memdata ]
# set memavail [regexp -inline -line {^MemAvailable:\s+(\d+)} $memdata {}]
set memavail [regexp -inline -line {^MemAvailable:\s+(\d+)} $memdata ]
if {[llength $memtotal] < 2 || [llength $memavail] < 2} {
puts "Failed to read system memory information."
return
}
set total [lindex $memtotal 1]
set avail [lindex $memavail 1]
set used [expr {$total - $avail}]
set percent_used [expr {($used * 100) / $total}]
if {$percent_used >= 90} {
puts "Memory usage is $percent_used%. Attempting to kill top memory process."
# Use ps to find the top memory-consuming process
set top_pid [exec sh -c "ps --no-headers -eo pid,%mem --sort=-%mem | head -n 1 | awk '{print \$1}'"]
if {[string is integer $top_pid]} {
puts "Killing process with PID: $top_pid"
exec kill -9 $top_pid
} else {
puts "Failed to identify top memory-consuming process."
}
} else {
puts "Memory usage is $percent_used%. No action required."
}
}
# Main monitor loop (check every minute)
while {1} {
check_memory
after 60000 ;# Wait 60,000 ms (60 seconds)
}