Issue
I have to write a script that prints every three seconds the % of CPU used by user or by system. If the user types a specific string, the output must switch back and forth.
How can I check for input without interrupting the output stream? The read command would stop it, I'm running out of ideas.
Solution
You can use the read command with the timeout option read -t
. For example the below script detects the string 'cc'. You can also specify the number of characters to read with -N
so that user does not have to press enter.
flag=0
while true; do
sleep 3
if [[ $flag -eq 0 ]];then
echo user
else
echo sys
fi
read -t 0.25 -N 2 input
if [[ $input = "cc" ]] ; then
[[ $flag -eq 0 ]] && flag=1 || flag=0
fi
done
Answered By - Samik