Cake771
Cake771

Reputation: 13

bash script to trap all interupts

so i have a simple lab exercise in class. Write and Interrupt/signal trapping program. this program will prompt user to guess the age of a grandmother. The user may guess as many times as possible. nothing will be able to terminate this program execpt when the user enters the right answer. so my question is this. I have trapped ctrl_c but is there some "trick" or command i can use to trap ALL the interrupts or do i need to just make a statement for each signal i want to trap.

age=88

trap ctrl_c INT

function ctrl_c()
{
echo "**Trapped CTRL-C"

}

while [ 1 ]

do

echo "Please enter Grandmothers age. "
read ageGuess
echo $ageGuess
if [ $ageGuess == $age ]
then
    echo "Exiting!"
    exit
fi

done

Upvotes: 0

Views: 92

Answers (1)

Andreas Louv
Andreas Louv

Reputation: 47099

Afaik trap xxx INT should be enough you can read more here and here, I will mention a few things about your script though:

The test command ([) uses = to compare two strings, not ==.

You should double-quote all your variables unless you are sure what will happen if they are not quoted, consider this:

a=a
b=a
# This will work since `$a` and `$b` contains a value
if [ $a = $b ]; then 
  echo hello
fi

This will fail since $c is empty and the statement will evaluate to: if [ = ]; then

if [ $c = $d ]; then
  echo fail 
fi

You should use true or : in your while loop:

while :; do

You should usually always use -r in read, and remember the shebang:

#!/bin/bash
age=88

trap ctrl_c INT

ctrl_c() {
  echo "**Trapped CTRL-C"
}

while :; do
  echo "Please enter Grandmothers age. "
  read -r ageGuess
  echo "$ageGuess"
  if [ "$ageGuess" = "$age" ]; then
    echo "Exiting!"
    exit
  fi
done

Actually the code could now use #!/bin/sh since it POSIX compatible.

Just note that you might want to use printf "%s\n" "$user_input" instead of echo "$user_input"

Upvotes: 1

Related Questions