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 thewhile
loop.From
help break
:So in your snippet, you can do:
Or even shorter:
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:In the function you can use get
spam
by using$1
: