'Bash script using dmesg to see a message on terminal when a mouse is plugged and unplugged
I am trying to get my hands dirty with bash scripting and dmesg. I want to write a script which does the following :
When the mouse is plugged in, and your script is run, it will print “mouse is present” when the mouse is unplugged and the script is run, it will say “mouse is not present”.
Here is the bash script that I came up with (This is my first bash script so please go easy :P)
#!/bin/bash
touch search_file.txt
FILENAME=search_file.txt
while true
do
dmesg -w > search_file.txt # read for changes in the kernel ring buffer and write to a file
if grep -Fxqi "mouse|disconnect" "$FILENAME" # look for the keywords
then
echo "Mouse is disconnected"
else
echo "Mouse is connected"
fi
done
I tried running this but I don't see the desired output.
Solution 1:[1]
You specified -w option on the dmesg command, which causes the program to wait for new messages. So the first instruction in your loop never completes.
You could try this :
#!/bin/bash
touch search_file.txt
FILENAME=search_file.txt
while true
do
dmesg > "$FILENAME" # read for changes in the kernel ring buffer and write to a file
if grep -Fxqi "mouse|disconnect" "$FILENAME" # look for the keywords
then
echo "Mouse is disconnected"
else
echo "Mouse is connected"
fi
done
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | nquincampoix |
