SIGINT SIGQUIT Bash script

187 views Asked by At

I need to write a script that has the following behaviour:

  • If the script receives the signal SIGINT, then the script increments the value of the counter by one and prints its value to the standard output.
  • If it receives the signal SIGQUIT, then it decreases the value of the counter by one and prints its value to standard output.
  • If the current value of the counter is less than -5 or more than +5, then the program terminates.
#!/bin/bash 
count=0
while [  $count -lt -5 ] && [ $count -gt 5 ];  do
    sleep 1
trap 'count=$(expr $count + 1)' SIGINT
echo $count
trap count=$(expr $count - 1) SIGQUIT
echo $count
done

I wrote this code, but I am not sure what I am doing wrong.

1

There are 1 answers

3
chepner On BEST ANSWER

You can set the traps at the beginning of your code to ensure they are created as early as possible (and more importantly, you don't need to reset them each time through the loop). Also, expr is obsolete for performing arithmetic in the shell; use arithmetic expressions instead.

The big problem, though, is that count can never simultaneously be less than -5 and greater than 5; you need to swap the comparisons.

trap 'count=$((count + 1))' SIGINT
trap 'count=$((count - 1))' SIGQUIT

count=0
# Loop will enter at least once, since -5 < 0 < 5
while [ "$count" -gt -5 ] && [ "$count" -lt 5 ]; do
    sleep 1
    echo "$count"
done