Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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'.

share|improve this question

3 Answers 3

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

share|improve this answer

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
share|improve this answer

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

do:

. 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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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