0

Hello here is my primary script. The test2.sh is just an echo "it worked"

what happens when I try and call from the original loop, it gets to the correct file then echo's infinite "it worked" where it should just be doing it once.

Any idea why? I really want to have another loop called outside of the main script that won't interfere, but still learning bash =P

#!/bin/bash
number=1

while true
do

if [ "$number" -eq "1" ]; then
    echo "hello 1!"
elif [ "$number" -eq "2" ]; then
    echo "hello 2!"
elif [ "$number" -eq "3" ]; then
    echo "hello 3!"
elif [ "$number" -eq "4" ]; then
   ./test2.sh & continue
fi
sleep 5


((number++))
echo $number
done

1 Answer 1

1

first observation & is not a logical operator, & runs the precedding command in the background. Use && for logical operations.

what you need is a break keyword not a continue keyword . If you use the break keyword, the loop will stop executing. The continue keyword only rexecutes the loop , and since number is 4 , this branch of code will always run elif [ "$number" -eq "4" ]; then

working code

#!/bin/bash
number=1

while true
do

if [ "$number" -eq "1" ]; then
    echo "hello 1!"
elif [ "$number" -eq "2" ]; then
    echo "hello 2!"
elif [ "$number" -eq "3" ]; then
    echo "hello 3!"
elif [ "$number" -eq "4" ]; then
   ./test2.sh && break
fi
sleep 5


((number++))
echo $number
done

or you can do this

for number in {1..4};do
   (( number == 4 )) && ./test2.sh || echo "$number"
   sleep 5
done
Sign up to request clarification or add additional context in comments.

4 Comments

so what I'm trying to do is continue the second script in the background but the loop still continue. That is why I'm trying the & and continue. Is this possible? for some reason, it keeps echoing the second sh and never continues on counting up 5, 6, 7, etc.
@JV You don't need the continue. If you use it (it should be on the next line) then it goes straight to the top of the top again - number will not be incremented.
You don't need continue and you don't need break.
Oh silly me! I had the continue there because I had an echo before I tested the second .sh file! I see now, since I'm calling another file, I no longer need the continue! Thanks guys :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.