Ubuntu – How to stop a infinite while loop running in background

bashscripts

Is there a option to let a endless while loop, when it's running in background as a function, stop and start running at any given moment with a local variable? I already did try a lot of options, only i was not able to find a neat solution. The only way i could get it working is reading a external text file from within the while loop. And at specified points in the program writing a 0 or 1 to that text file.

What i'm doing now is:

    #!/bin/bash

intr(){ while true                  # function endless while loop start 
        do 
        sleep 0.5                   # execute function every x time
        var1=`grep "1" 0or1.txt`    # read file 0or1.txt 
        if [ -n "$var1" ] ; then    # if text =1 execute function, 
        # do some magic..
        fi
        done
        }                           # end function
        intr &                      # execute function as bg process

#some code                          # located some where in the script
echo "1" > 0or1.txt                 # write 1 to start function 
#some code                          # this should be a local variable??


#some code                          # located some where in the script               
echo "0" > 0or1.txt                 # write 0 to stop function
#some code                          # this should be a local variable??

Best Answer

Use the break builtin to stop the while loop.

From help break:

break: break [n]

Exit for, while, or until loops.

Exit a FOR, WHILE or UNTIL loop.  If N is specified, break N enclosing
loops.

Exit Status:
The exit status is 0 unless N is not greater than or equal to 1.

So in your snippet, you can do:

while :; do
    if [ -n "$var1" ] ; then
        break
    fi
done

Or even shorter:

while :; do
    [ -n "$var1" ] && break
done

To pass any input to the function, use positional parameters i.e. arguments. The first argument can be retrieved by $1, second $2 and so on.

For example, if you call function foobar by:

foobar spam

In the function you can use get spam by using $1:

$ foobar () { echo "This is $1" ;}

$ foobar spam
This is spam
Related Question