for example consider the following situation::

I need to print some numbers randomly one after the other with a time interval of 5 seconds between each, and I need to terminate the terminal process of printing numbers if i encounter an output of '2'. Is it possible.

I know I could do the same in c, c++, java, etc. etc,. But I would like to do it using bash script.

Note:: If only 'after' I encounter an 'output' of '2'(or anything) then the process needs to be terminated, I stress this because 'I need to terminate the terminal process for a particular outcome'.


a bash shell knows its parent process, so you could do:

(( number == 2 )) && kill $PPID

ref: http://www.gnu.org/software/bash/manual/bashref.html#Bash-Variables


You can use a simple if statement to do that:

# your file reading code goes here, make sure $output is set
if [ $output -eq 2 ]; then return; fi

What you want is to kill the shell from which you run the script. This is a bit tricky as running a script will spawn another shell, and the trivial methods of killing it (kill -9 $$ or exit) will work on the spawned shell, not the one invoked by the terminal.

The only reliable way I found of doing so is to source your script instead of running it. So instead of:

bash script.sh


. script.sh

this will cause stuff to run in the invoking shell, not the spawned one.

The script itself is easy as seen in the other answer:

while true; do sleep 1; number=$RANDOM; echo $number; if [ 2 = 2 ]; then exit; fi; done

Actually if you run this as a one-liner in your current shell, it will close the terminal when it sees a value of 2.

You didn't say where the random numbers will come from; I used the RANDOM bash built-in which outputs integers in the range 0-32767.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.