2

I'm looking to repeat this code until I stop it, either by setting a time for which it repeats, pressing ^c, or set number of iterations, and then output the result of repeating it. The code should feed into itself, such that inputting the variables 5 and 2 the first time would result in restarting the script with 5 and 2.25 as the variables. The script helps determine the square root of a number, with one guess.

#!/bin/bash
echo -n "Please enter the number you need to find the square root for and press [ENTER]: "
read fin
echo -n "Please enter guess and press [ENTER]: "
read gues
var=$(echo "$fin/$gues" | bc -l )
var1=$(echo "$var+$gues" | bc -l )
var2=$(echo "$var1/2" | bc -l )
echo $var2

1 Answers1

2

You'd need to put that code into an infinite loop, such as:

while 1; do
  # Rest of code
  ...
done

In order to stop when Ctrl+C is hit, what you're actually doing is to trap a signal (concretely, SIGINT). You'd need to define a trap so it triggers when you hit that combination of keys.

For more info about traps, you can have a look here, which includes a SIGINT example and how you can print anything after catching it.

trap [COMMANDS] [SIGNALS]

This instructs the trap command to catch the listed SIGNALS, which may be signal names with or without the SIG prefix, or signal numbers. If a signal is 0 or EXIT, the COMMANDS are executed when the shell exits. If one of the signals is DEBUG, the list of COMMANDS is executed after every simple command. A signal may also be specified as ERR; in that case COMMANDS are executed each time a simple command exits with a non-zero status. Note that these commands will not be executed when the non-zero exit status comes from part of an if statement, or from a while or until loop. Neither will they be executed if a logical AND (&&) or OR (||) result in a non-zero exit code, or when a command's return status is inverted using the ! operator.

nKn
  • 5,832