Bash – How to create an infinite loop that kills a process if something is found in dmesg

bashlinuxscripting

I need to create a while loop that if dmesg returns some/any value, then it should kill a determined process.

Here is what I have.

#!/bin/bash
while [ 1 ];
do

BUG=$(dmesg | grep "BUG: workqueue lockup" &> /dev/null)

    if [ ! -z "$BUG" ]; then
   killall someprocessname

else
    break
    fi
    done

I don't know if instead of ! -z I should do [ test -n "$BUG" ]

I think with -n it says something about expecting a binary.

I don't know if the script will even work because the BUG lockup halts every process, but still there are few more lines in dmesg until the computer gets completely borked – maybe I can catch-up and kill the process.

Best Answer

Some issues:

  • You are running this in a busy loop, which will consume as much resources as it can. This is one instance where sleeping could conceivably be justified.
  • However, recent versions of dmesg have a flag to follow the output, so you could rewrite the whole thing as (untested)

    while true
    do
        dmesg --follow | tail --follow --lines=0 | grep --quiet 'BUG: workqueue lockup'
        killall someprocessname
    done
    
  • The code should be indented to be readable.
  • It is really strange, but [ is the same as test - see help [.
Related Question