'Run while loop in background and execute the entire script - Bash
I am trying to run a condition at specific interval in while loop but the issue is that it is only executing the test function, I am trying that the test function keep on getting executed at specific interval and the script should move to the next function as well keeping test function running in the background. Any help would be appreciated
test(){
while true;
do
echo "Hello"
sleep 5
done
}
function2(){
echo "I am inside function2"
}
test
function2
Solution 1:[1]
You can tell bash to run a command in a separate subshell, asynchronously, with a single trailing ampersand &. So you can make test run separately like this:
test(){
while true;
do
echo "Hello"
sleep 5
done
}
function2(){
echo "I am inside function2"
}
test &
function2
However, this will cause the script to terminate before test is finished running! You can make the program wait for test & to finish at a later point in the program by using wait:
test(){
while true;
do
echo "Hello"
sleep 5
done
}
function2(){
echo "I am inside function2"
}
test & p1=$!
function2
wait $p1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Gbox4 |
