0

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.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
JohnSnow
  • 17
  • 4
  • What problem are you seeing? What does your code do now? Please [edit your question](https://stackoverflow.com/posts/41466096/edit) to add detail. Thanks! --- I do note that, in the second `trap`, you may want quotes around the `count=...` expression. – cxw Jan 04 '17 at 14:26

1 Answers1

0

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
chepner
  • 497,756
  • 71
  • 530
  • 681
  • `n=$((n + 1))` → `((n += 1))` – pynexj Jan 04 '17 at 15:15
  • I'm sticking with POSIX-supported constructs for this answer, in keeping with the original code, but `(( n+=1 ))` or even `((n++))` is certainly an option for `bash`. – chepner Jan 04 '17 at 15:46
  • You could even write `: $(( n+= 1))` (as long as `n` was previously defined), but a POSIX-compliant shell is not required to recognize either pre- or post-fix versions of `++`. – chepner Jan 04 '17 at 16:40